home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.5 / lib-tk / Tkinter.py < prev    next >
Encoding:
Python Source  |  2007-05-02  |  154.3 KB  |  3,763 lines

  1. """Wrapper functions for Tcl/Tk.
  2.  
  3. Tkinter provides classes which allow the display, positioning and
  4. control of widgets. Toplevel widgets are Tk and Toplevel. Other
  5. widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
  6. Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
  7. LabelFrame and PanedWindow.
  8.  
  9. Properties of the widgets are specified with keyword arguments.
  10. Keyword arguments have the same name as the corresponding resource
  11. under Tk.
  12.  
  13. Widgets are positioned with one of the geometry managers Place, Pack
  14. or Grid. These managers can be called with methods place, pack, grid
  15. available in every Widget.
  16.  
  17. Actions are bound to events by resources (e.g. keyword argument
  18. command) or with the method bind.
  19.  
  20. Example (Hello, World):
  21. import Tkinter
  22. from Tkconstants import *
  23. tk = Tkinter.Tk()
  24. frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
  25. frame.pack(fill=BOTH,expand=1)
  26. label = Tkinter.Label(frame, text="Hello, World")
  27. label.pack(fill=X, expand=1)
  28. button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
  29. button.pack(side=BOTTOM)
  30. tk.mainloop()
  31. """
  32.  
  33. __version__ = "$Revision: 50704 $"
  34.  
  35. import sys
  36. if sys.platform == "win32":
  37.     import FixTk # Attempt to configure Tcl/Tk without requiring PATH
  38. try:
  39.     import _tkinter
  40. except ImportError, msg:
  41.     raise ImportError, str(msg) + ', please install the python-tk package'
  42. tkinter = _tkinter # b/w compat for export
  43. TclError = _tkinter.TclError
  44. from types import *
  45. from Tkconstants import *
  46. try:
  47.     import MacOS; _MacOS = MacOS; del MacOS
  48. except ImportError:
  49.     _MacOS = None
  50.  
  51. wantobjects = 1
  52.  
  53. TkVersion = float(_tkinter.TK_VERSION)
  54. TclVersion = float(_tkinter.TCL_VERSION)
  55.  
  56. READABLE = _tkinter.READABLE
  57. WRITABLE = _tkinter.WRITABLE
  58. EXCEPTION = _tkinter.EXCEPTION
  59.  
  60. # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  61. try: _tkinter.createfilehandler
  62. except AttributeError: _tkinter.createfilehandler = None
  63. try: _tkinter.deletefilehandler
  64. except AttributeError: _tkinter.deletefilehandler = None
  65.  
  66.  
  67. def _flatten(tuple):
  68.     """Internal function."""
  69.     res = ()
  70.     for item in tuple:
  71.         if type(item) in (TupleType, ListType):
  72.             res = res + _flatten(item)
  73.         elif item is not None:
  74.             res = res + (item,)
  75.     return res
  76.  
  77. try: _flatten = _tkinter._flatten
  78. except AttributeError: pass
  79.  
  80. def _cnfmerge(cnfs):
  81.     """Internal function."""
  82.     if type(cnfs) is DictionaryType:
  83.         return cnfs
  84.     elif type(cnfs) in (NoneType, StringType):
  85.         return cnfs
  86.     else:
  87.         cnf = {}
  88.         for c in _flatten(cnfs):
  89.             try:
  90.                 cnf.update(c)
  91.             except (AttributeError, TypeError), msg:
  92.                 print "_cnfmerge: fallback due to:", msg
  93.                 for k, v in c.items():
  94.                     cnf[k] = v
  95.         return cnf
  96.  
  97. try: _cnfmerge = _tkinter._cnfmerge
  98. except AttributeError: pass
  99.  
  100. class Event:
  101.     """Container for the properties of an event.
  102.  
  103.     Instances of this type are generated if one of the following events occurs:
  104.  
  105.     KeyPress, KeyRelease - for keyboard events
  106.     ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
  107.     Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
  108.     Colormap, Gravity, Reparent, Property, Destroy, Activate,
  109.     Deactivate - for window events.
  110.  
  111.     If a callback function for one of these events is registered
  112.     using bind, bind_all, bind_class, or tag_bind, the callback is
  113.     called with an Event as first argument. It will have the
  114.     following attributes (in braces are the event types for which
  115.     the attribute is valid):
  116.  
  117.         serial - serial number of event
  118.     num - mouse button pressed (ButtonPress, ButtonRelease)
  119.     focus - whether the window has the focus (Enter, Leave)
  120.     height - height of the exposed window (Configure, Expose)
  121.     width - width of the exposed window (Configure, Expose)
  122.     keycode - keycode of the pressed key (KeyPress, KeyRelease)
  123.     state - state of the event as a number (ButtonPress, ButtonRelease,
  124.                             Enter, KeyPress, KeyRelease,
  125.                             Leave, Motion)
  126.     state - state as a string (Visibility)
  127.     time - when the event occurred
  128.     x - x-position of the mouse
  129.     y - y-position of the mouse
  130.     x_root - x-position of the mouse on the screen
  131.              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  132.     y_root - y-position of the mouse on the screen
  133.              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  134.     char - pressed character (KeyPress, KeyRelease)
  135.     send_event - see X/Windows documentation
  136.     keysym - keysym of the event as a string (KeyPress, KeyRelease)
  137.     keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
  138.     type - type of the event as a number
  139.     widget - widget in which the event occurred
  140.     delta - delta of wheel movement (MouseWheel)
  141.     """
  142.     pass
  143.  
  144. _support_default_root = 1
  145. _default_root = None
  146.  
  147. def NoDefaultRoot():
  148.     """Inhibit setting of default root window.
  149.  
  150.     Call this function to inhibit that the first instance of
  151.     Tk is used for windows without an explicit parent window.
  152.     """
  153.     global _support_default_root
  154.     _support_default_root = 0
  155.     global _default_root
  156.     _default_root = None
  157.     del _default_root
  158.  
  159. def _tkerror(err):
  160.     """Internal function."""
  161.     pass
  162.  
  163. def _exit(code='0'):
  164.     """Internal function. Calling it will throw the exception SystemExit."""
  165.     raise SystemExit, code
  166.  
  167. _varnum = 0
  168. class Variable:
  169.     """Class to define value holders for e.g. buttons.
  170.  
  171.     Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
  172.     that constrain the type of the value returned from get()."""
  173.     _default = ""
  174.     def __init__(self, master=None, value=None, name=None):
  175.         """Construct a variable
  176.  
  177.         MASTER can be given as master widget.
  178.         VALUE is an optional value (defaults to "")
  179.         NAME is an optional Tcl name (defaults to PY_VARnum).
  180.  
  181.         If NAME matches an existing variable and VALUE is omitted
  182.         then the existing value is retained.
  183.         """
  184.         global _varnum
  185.         if not master:
  186.             master = _default_root
  187.         self._master = master
  188.         self._tk = master.tk
  189.         if name:
  190.             self._name = name
  191.         else:
  192.             self._name = 'PY_VAR' + repr(_varnum)
  193.             _varnum += 1
  194.         if value != None:
  195.             self.set(value)
  196.         elif not self._tk.call("info", "exists", self._name):
  197.             self.set(self._default)
  198.     def __del__(self):
  199.         """Unset the variable in Tcl."""
  200.         self._tk.globalunsetvar(self._name)
  201.     def __str__(self):
  202.         """Return the name of the variable in Tcl."""
  203.         return self._name
  204.     def set(self, value):
  205.         """Set the variable to VALUE."""
  206.         return self._tk.globalsetvar(self._name, value)
  207.     def get(self):
  208.         """Return value of variable."""
  209.         return self._tk.globalgetvar(self._name)
  210.     def trace_variable(self, mode, callback):
  211.         """Define a trace callback for the variable.
  212.  
  213.         MODE is one of "r", "w", "u" for read, write, undefine.
  214.         CALLBACK must be a function which is called when
  215.         the variable is read, written or undefined.
  216.  
  217.         Return the name of the callback.
  218.         """
  219.         cbname = self._master._register(callback)
  220.         self._tk.call("trace", "variable", self._name, mode, cbname)
  221.         return cbname
  222.     trace = trace_variable
  223.     def trace_vdelete(self, mode, cbname):
  224.         """Delete the trace callback for a variable.
  225.  
  226.         MODE is one of "r", "w", "u" for read, write, undefine.
  227.         CBNAME is the name of the callback returned from trace_variable or trace.
  228.         """
  229.         self._tk.call("trace", "vdelete", self._name, mode, cbname)
  230.         self._master.deletecommand(cbname)
  231.     def trace_vinfo(self):
  232.         """Return all trace callback information."""
  233.         return map(self._tk.split, self._tk.splitlist(
  234.             self._tk.call("trace", "vinfo", self._name)))
  235.     def __eq__(self, other):
  236.         """Comparison for equality (==).
  237.  
  238.         Note: if the Variable's master matters to behavior
  239.         also compare self._master == other._master
  240.         """
  241.         return self.__class__.__name__ == other.__class__.__name__ \
  242.             and self._name == other._name
  243.  
  244. class StringVar(Variable):
  245.     """Value holder for strings variables."""
  246.     _default = ""
  247.     def __init__(self, master=None, value=None, name=None):
  248.         """Construct a string variable.
  249.  
  250.         MASTER can be given as master widget.
  251.         VALUE is an optional value (defaults to "")
  252.         NAME is an optional Tcl name (defaults to PY_VARnum).
  253.  
  254.         If NAME matches an existing variable and VALUE is omitted
  255.         then the existing value is retained.
  256.         """
  257.         Variable.__init__(self, master, value, name)
  258.  
  259.     def get(self):
  260.         """Return value of variable as string."""
  261.         value = self._tk.globalgetvar(self._name)
  262.         if isinstance(value, basestring):
  263.             return value
  264.         return str(value)
  265.  
  266. class IntVar(Variable):
  267.     """Value holder for integer variables."""
  268.     _default = 0
  269.     def __init__(self, master=None, value=None, name=None):
  270.         """Construct an integer variable.
  271.  
  272.         MASTER can be given as master widget.
  273.         VALUE is an optional value (defaults to 0)
  274.         NAME is an optional Tcl name (defaults to PY_VARnum).
  275.  
  276.         If NAME matches an existing variable and VALUE is omitted
  277.         then the existing value is retained.
  278.         """
  279.         Variable.__init__(self, master, value, name)
  280.  
  281.     def set(self, value):
  282.         """Set the variable to value, converting booleans to integers."""
  283.         if isinstance(value, bool):
  284.             value = int(value)
  285.         return Variable.set(self, value)
  286.  
  287.     def get(self):
  288.         """Return the value of the variable as an integer."""
  289.         return getint(self._tk.globalgetvar(self._name))
  290.  
  291. class DoubleVar(Variable):
  292.     """Value holder for float variables."""
  293.     _default = 0.0
  294.     def __init__(self, master=None, value=None, name=None):
  295.         """Construct a float variable.
  296.  
  297.         MASTER can be given as master widget.
  298.         VALUE is an optional value (defaults to 0.0)
  299.         NAME is an optional Tcl name (defaults to PY_VARnum).
  300.  
  301.         If NAME matches an existing variable and VALUE is omitted
  302.         then the existing value is retained.
  303.         """
  304.         Variable.__init__(self, master, value, name)
  305.  
  306.     def get(self):
  307.         """Return the value of the variable as a float."""
  308.         return getdouble(self._tk.globalgetvar(self._name))
  309.  
  310. class BooleanVar(Variable):
  311.     """Value holder for boolean variables."""
  312.     _default = False
  313.     def __init__(self, master=None, value=None, name=None):
  314.         """Construct a boolean variable.
  315.  
  316.         MASTER can be given as master widget.
  317.         VALUE is an optional value (defaults to False)
  318.         NAME is an optional Tcl name (defaults to PY_VARnum).
  319.  
  320.         If NAME matches an existing variable and VALUE is omitted
  321.         then the existing value is retained.
  322.         """
  323.         Variable.__init__(self, master, value, name)
  324.  
  325.     def get(self):
  326.         """Return the value of the variable as a bool."""
  327.         return self._tk.getboolean(self._tk.globalgetvar(self._name))
  328.  
  329. def mainloop(n=0):
  330.     """Run the main loop of Tcl."""
  331.     _default_root.tk.mainloop(n)
  332.  
  333. getint = int
  334.  
  335. getdouble = float
  336.  
  337. def getboolean(s):
  338.     """Convert true and false to integer values 1 and 0."""
  339.     return _default_root.tk.getboolean(s)
  340.  
  341. # Methods defined on both toplevel and interior widgets
  342. class Misc:
  343.     """Internal class.
  344.  
  345.     Base class which defines methods common for interior widgets."""
  346.  
  347.     # XXX font command?
  348.     _tclCommands = None
  349.     def destroy(self):
  350.         """Internal function.
  351.  
  352.         Delete all Tcl commands created for
  353.         this widget in the Tcl interpreter."""
  354.         if self._tclCommands is not None:
  355.             for name in self._tclCommands:
  356.                 #print '- Tkinter: deleted command', name
  357.                 self.tk.deletecommand(name)
  358.             self._tclCommands = None
  359.     def deletecommand(self, name):
  360.         """Internal function.
  361.  
  362.         Delete the Tcl command provided in NAME."""
  363.         #print '- Tkinter: deleted command', name
  364.         self.tk.deletecommand(name)
  365.         try:
  366.             self._tclCommands.remove(name)
  367.         except ValueError:
  368.             pass
  369.     def tk_strictMotif(self, boolean=None):
  370.         """Set Tcl internal variable, whether the look and feel
  371.         should adhere to Motif.
  372.  
  373.         A parameter of 1 means adhere to Motif (e.g. no color
  374.         change if mouse passes over slider).
  375.         Returns the set value."""
  376.         return self.tk.getboolean(self.tk.call(
  377.             'set', 'tk_strictMotif', boolean))
  378.     def tk_bisque(self):
  379.         """Change the color scheme to light brown as used in Tk 3.6 and before."""
  380.         self.tk.call('tk_bisque')
  381.     def tk_setPalette(self, *args, **kw):
  382.         """Set a new color scheme for all widget elements.
  383.  
  384.         A single color as argument will cause that all colors of Tk
  385.         widget elements are derived from this.
  386.         Alternatively several keyword parameters and its associated
  387.         colors can be given. The following keywords are valid:
  388.         activeBackground, foreground, selectColor,
  389.         activeForeground, highlightBackground, selectBackground,
  390.         background, highlightColor, selectForeground,
  391.         disabledForeground, insertBackground, troughColor."""
  392.         self.tk.call(('tk_setPalette',)
  393.               + _flatten(args) + _flatten(kw.items()))
  394.     def tk_menuBar(self, *args):
  395.         """Do not use. Needed in Tk 3.6 and earlier."""
  396.         pass # obsolete since Tk 4.0
  397.     def wait_variable(self, name='PY_VAR'):
  398.         """Wait until the variable is modified.
  399.  
  400.         A parameter of type IntVar, StringVar, DoubleVar or
  401.         BooleanVar must be given."""
  402.         self.tk.call('tkwait', 'variable', name)
  403.     waitvar = wait_variable # XXX b/w compat
  404.     def wait_window(self, window=None):
  405.         """Wait until a WIDGET is destroyed.
  406.  
  407.         If no parameter is given self is used."""
  408.         if window is None:
  409.             window = self
  410.         self.tk.call('tkwait', 'window', window._w)
  411.     def wait_visibility(self, window=None):
  412.         """Wait until the visibility of a WIDGET changes
  413.         (e.g. it appears).
  414.  
  415.         If no parameter is given self is used."""
  416.         if window is None:
  417.             window = self
  418.         self.tk.call('tkwait', 'visibility', window._w)
  419.     def setvar(self, name='PY_VAR', value='1'):
  420.         """Set Tcl variable NAME to VALUE."""
  421.         self.tk.setvar(name, value)
  422.     def getvar(self, name='PY_VAR'):
  423.         """Return value of Tcl variable NAME."""
  424.         return self.tk.getvar(name)
  425.     getint = int
  426.     getdouble = float
  427.     def getboolean(self, s):
  428.         """Return a boolean value for Tcl boolean values true and false given as parameter."""
  429.         return self.tk.getboolean(s)
  430.     def focus_set(self):
  431.         """Direct input focus to this widget.
  432.  
  433.         If the application currently does not have the focus
  434.         this widget will get the focus if the application gets
  435.         the focus through the window manager."""
  436.         self.tk.call('focus', self._w)
  437.     focus = focus_set # XXX b/w compat?
  438.     def focus_force(self):
  439.         """Direct input focus to this widget even if the
  440.         application does not have the focus. Use with
  441.         caution!"""
  442.         self.tk.call('focus', '-force', self._w)
  443.     def focus_get(self):
  444.         """Return the widget which has currently the focus in the
  445.         application.
  446.  
  447.         Use focus_displayof to allow working with several
  448.         displays. Return None if application does not have
  449.         the focus."""
  450.         name = self.tk.call('focus')
  451.         if name == 'none' or not name: return None
  452.         return self._nametowidget(name)
  453.     def focus_displayof(self):
  454.         """Return the widget which has currently the focus on the
  455.         display where this widget is located.
  456.  
  457.         Return None if the application does not have the focus."""
  458.         name = self.tk.call('focus', '-displayof', self._w)
  459.         if name == 'none' or not name: return None
  460.         return self._nametowidget(name)
  461.     def focus_lastfor(self):
  462.         """Return the widget which would have the focus if top level
  463.         for this widget gets the focus from the window manager."""
  464.         name = self.tk.call('focus', '-lastfor', self._w)
  465.         if name == 'none' or not name: return None
  466.         return self._nametowidget(name)
  467.     def tk_focusFollowsMouse(self):
  468.         """The widget under mouse will get automatically focus. Can not
  469.         be disabled easily."""
  470.         self.tk.call('tk_focusFollowsMouse')
  471.     def tk_focusNext(self):
  472.         """Return the next widget in the focus order which follows
  473.         widget which has currently the focus.
  474.  
  475.         The focus order first goes to the next child, then to
  476.         the children of the child recursively and then to the
  477.         next sibling which is higher in the stacking order.  A
  478.         widget is omitted if it has the takefocus resource set
  479.         to 0."""
  480.         name = self.tk.call('tk_focusNext', self._w)
  481.         if not name: return None
  482.         return self._nametowidget(name)
  483.     def tk_focusPrev(self):
  484.         """Return previous widget in the focus order. See tk_focusNext for details."""
  485.         name = self.tk.call('tk_focusPrev', self._w)
  486.         if not name: return None
  487.         return self._nametowidget(name)
  488.     def after(self, ms, func=None, *args):
  489.         """Call function once after given time.
  490.  
  491.         MS specifies the time in milliseconds. FUNC gives the
  492.         function which shall be called. Additional parameters
  493.         are given as parameters to the function call.  Return
  494.         identifier to cancel scheduling with after_cancel."""
  495.         if not func:
  496.             # I'd rather use time.sleep(ms*0.001)
  497.             self.tk.call('after', ms)
  498.         else:
  499.             def callit():
  500.                 try:
  501.                     func(*args)
  502.                 finally:
  503.                     try:
  504.                         self.deletecommand(name)
  505.                     except TclError:
  506.                         pass
  507.             name = self._register(callit)
  508.             return self.tk.call('after', ms, name)
  509.     def after_idle(self, func, *args):
  510.         """Call FUNC once if the Tcl main loop has no event to
  511.         process.
  512.  
  513.         Return an identifier to cancel the scheduling with
  514.         after_cancel."""
  515.         return self.after('idle', func, *args)
  516.     def after_cancel(self, id):
  517.         """Cancel scheduling of function identified with ID.
  518.  
  519.         Identifier returned by after or after_idle must be
  520.         given as first parameter."""
  521.         try:
  522.             data = self.tk.call('after', 'info', id)
  523.             # In Tk 8.3, splitlist returns: (script, type)
  524.             # In Tk 8.4, splitlist may return (script, type) or (script,)
  525.             script = self.tk.splitlist(data)[0]
  526.             self.deletecommand(script)
  527.         except TclError:
  528.             pass
  529.         self.tk.call('after', 'cancel', id)
  530.     def bell(self, displayof=0):
  531.         """Ring a display's bell."""
  532.         self.tk.call(('bell',) + self._displayof(displayof))
  533.  
  534.     # Clipboard handling:
  535.     def clipboard_get(self, **kw):
  536.         """Retrieve data from the clipboard on window's display.
  537.  
  538.         The window keyword defaults to the root window of the Tkinter
  539.         application.
  540.  
  541.         The type keyword specifies the form in which the data is
  542.         to be returned and should be an atom name such as STRING
  543.         or FILE_NAME.  Type defaults to STRING.
  544.  
  545.         This command is equivalent to:
  546.  
  547.         selection_get(CLIPBOARD)
  548.         """
  549.         return self.tk.call(('clipboard', 'get') + self._options(kw))
  550.  
  551.     def clipboard_clear(self, **kw):
  552.         """Clear the data in the Tk clipboard.
  553.  
  554.         A widget specified for the optional displayof keyword
  555.         argument specifies the target display."""
  556.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  557.         self.tk.call(('clipboard', 'clear') + self._options(kw))
  558.     def clipboard_append(self, string, **kw):
  559.         """Append STRING to the Tk clipboard.
  560.  
  561.         A widget specified at the optional displayof keyword
  562.         argument specifies the target display. The clipboard
  563.         can be retrieved with selection_get."""
  564.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  565.         self.tk.call(('clipboard', 'append') + self._options(kw)
  566.               + ('--', string))
  567.     # XXX grab current w/o window argument
  568.     def grab_current(self):
  569.         """Return widget which has currently the grab in this application
  570.         or None."""
  571.         name = self.tk.call('grab', 'current', self._w)
  572.         if not name: return None
  573.         return self._nametowidget(name)
  574.     def grab_release(self):
  575.         """Release grab for this widget if currently set."""
  576.         self.tk.call('grab', 'release', self._w)
  577.     def grab_set(self):
  578.         """Set grab for this widget.
  579.  
  580.         A grab directs all events to this and descendant
  581.         widgets in the application."""
  582.         self.tk.call('grab', 'set', self._w)
  583.     def grab_set_global(self):
  584.         """Set global grab for this widget.
  585.  
  586.         A global grab directs all events to this and
  587.         descendant widgets on the display. Use with caution -
  588.         other applications do not get events anymore."""
  589.         self.tk.call('grab', 'set', '-global', self._w)
  590.     def grab_status(self):
  591.         """Return None, "local" or "global" if this widget has
  592.         no, a local or a global grab."""
  593.         status = self.tk.call('grab', 'status', self._w)
  594.         if status == 'none': status = None
  595.         return status
  596.     def lower(self, belowThis=None):
  597.         """Lower this widget in the stacking order."""
  598.         self.tk.call('lower', self._w, belowThis)
  599.     def option_add(self, pattern, value, priority = None):
  600.         """Set a VALUE (second parameter) for an option
  601.         PATTERN (first parameter).
  602.  
  603.         An optional third parameter gives the numeric priority
  604.         (defaults to 80)."""
  605.         self.tk.call('option', 'add', pattern, value, priority)
  606.     def option_clear(self):
  607.         """Clear the option database.
  608.  
  609.         It will be reloaded if option_add is called."""
  610.         self.tk.call('option', 'clear')
  611.     def option_get(self, name, className):
  612.         """Return the value for an option NAME for this widget
  613.         with CLASSNAME.
  614.  
  615.         Values with higher priority override lower values."""
  616.         return self.tk.call('option', 'get', self._w, name, className)
  617.     def option_readfile(self, fileName, priority = None):
  618.         """Read file FILENAME into the option database.
  619.  
  620.         An optional second parameter gives the numeric
  621.         priority."""
  622.         self.tk.call('option', 'readfile', fileName, priority)
  623.     def selection_clear(self, **kw):
  624.         """Clear the current X selection."""
  625.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  626.         self.tk.call(('selection', 'clear') + self._options(kw))
  627.     def selection_get(self, **kw):
  628.         """Return the contents of the current X selection.
  629.  
  630.         A keyword parameter selection specifies the name of
  631.         the selection and defaults to PRIMARY.  A keyword
  632.         parameter displayof specifies a widget on the display
  633.         to use."""
  634.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  635.         return self.tk.call(('selection', 'get') + self._options(kw))
  636.     def selection_handle(self, command, **kw):
  637.         """Specify a function COMMAND to call if the X
  638.         selection owned by this widget is queried by another
  639.         application.
  640.  
  641.         This function must return the contents of the
  642.         selection. The function will be called with the
  643.         arguments OFFSET and LENGTH which allows the chunking
  644.         of very long selections. The following keyword
  645.         parameters can be provided:
  646.         selection - name of the selection (default PRIMARY),
  647.         type - type of the selection (e.g. STRING, FILE_NAME)."""
  648.         name = self._register(command)
  649.         self.tk.call(('selection', 'handle') + self._options(kw)
  650.               + (self._w, name))
  651.     def selection_own(self, **kw):
  652.         """Become owner of X selection.
  653.  
  654.         A keyword parameter selection specifies the name of
  655.         the selection (default PRIMARY)."""
  656.         self.tk.call(('selection', 'own') +
  657.                  self._options(kw) + (self._w,))
  658.     def selection_own_get(self, **kw):
  659.         """Return owner of X selection.
  660.  
  661.         The following keyword parameter can
  662.         be provided:
  663.         selection - name of the selection (default PRIMARY),
  664.         type - type of the selection (e.g. STRING, FILE_NAME)."""
  665.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  666.         name = self.tk.call(('selection', 'own') + self._options(kw))
  667.         if not name: return None
  668.         return self._nametowidget(name)
  669.     def send(self, interp, cmd, *args):
  670.         """Send Tcl command CMD to different interpreter INTERP to be executed."""
  671.         return self.tk.call(('send', interp, cmd) + args)
  672.     def lower(self, belowThis=None):
  673.         """Lower this widget in the stacking order."""
  674.         self.tk.call('lower', self._w, belowThis)
  675.     def tkraise(self, aboveThis=None):
  676.         """Raise this widget in the stacking order."""
  677.         self.tk.call('raise', self._w, aboveThis)
  678.     lift = tkraise
  679.     def colormodel(self, value=None):
  680.         """Useless. Not implemented in Tk."""
  681.         return self.tk.call('tk', 'colormodel', self._w, value)
  682.     def winfo_atom(self, name, displayof=0):
  683.         """Return integer which represents atom NAME."""
  684.         args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  685.         return getint(self.tk.call(args))
  686.     def winfo_atomname(self, id, displayof=0):
  687.         """Return name of atom with identifier ID."""
  688.         args = ('winfo', 'atomname') \
  689.                + self._displayof(displayof) + (id,)
  690.         return self.tk.call(args)
  691.     def winfo_cells(self):
  692.         """Return number of cells in the colormap for this widget."""
  693.         return getint(
  694.             self.tk.call('winfo', 'cells', self._w))
  695.     def winfo_children(self):
  696.         """Return a list of all widgets which are children of this widget."""
  697.         result = []
  698.         for child in self.tk.splitlist(
  699.             self.tk.call('winfo', 'children', self._w)):
  700.             try:
  701.                 # Tcl sometimes returns extra windows, e.g. for
  702.                 # menus; those need to be skipped
  703.                 result.append(self._nametowidget(child))
  704.             except KeyError:
  705.                 pass
  706.         return result
  707.  
  708.     def winfo_class(self):
  709.         """Return window class name of this widget."""
  710.         return self.tk.call('winfo', 'class', self._w)
  711.     def winfo_colormapfull(self):
  712.         """Return true if at the last color request the colormap was full."""
  713.         return self.tk.getboolean(
  714.             self.tk.call('winfo', 'colormapfull', self._w))
  715.     def winfo_containing(self, rootX, rootY, displayof=0):
  716.         """Return the widget which is at the root coordinates ROOTX, ROOTY."""
  717.         args = ('winfo', 'containing') \
  718.                + self._displayof(displayof) + (rootX, rootY)
  719.         name = self.tk.call(args)
  720.         if not name: return None
  721.         return self._nametowidget(name)
  722.     def winfo_depth(self):
  723.         """Return the number of bits per pixel."""
  724.         return getint(self.tk.call('winfo', 'depth', self._w))
  725.     def winfo_exists(self):
  726.         """Return true if this widget exists."""
  727.         return getint(
  728.             self.tk.call('winfo', 'exists', self._w))
  729.     def winfo_fpixels(self, number):
  730.         """Return the number of pixels for the given distance NUMBER
  731.         (e.g. "3c") as float."""
  732.         return getdouble(self.tk.call(
  733.             'winfo', 'fpixels', self._w, number))
  734.     def winfo_geometry(self):
  735.         """Return geometry string for this widget in the form "widthxheight+X+Y"."""
  736.         return self.tk.call('winfo', 'geometry', self._w)
  737.     def winfo_height(self):
  738.         """Return height of this widget."""
  739.         return getint(
  740.             self.tk.call('winfo', 'height', self._w))
  741.     def winfo_id(self):
  742.         """Return identifier ID for this widget."""
  743.         return self.tk.getint(
  744.             self.tk.call('winfo', 'id', self._w))
  745.     def winfo_interps(self, displayof=0):
  746.         """Return the name of all Tcl interpreters for this display."""
  747.         args = ('winfo', 'interps') + self._displayof(displayof)
  748.         return self.tk.splitlist(self.tk.call(args))
  749.     def winfo_ismapped(self):
  750.         """Return true if this widget is mapped."""
  751.         return getint(
  752.             self.tk.call('winfo', 'ismapped', self._w))
  753.     def winfo_manager(self):
  754.         """Return the window mananger name for this widget."""
  755.         return self.tk.call('winfo', 'manager', self._w)
  756.     def winfo_name(self):
  757.         """Return the name of this widget."""
  758.         return self.tk.call('winfo', 'name', self._w)
  759.     def winfo_parent(self):
  760.         """Return the name of the parent of this widget."""
  761.         return self.tk.call('winfo', 'parent', self._w)
  762.     def winfo_pathname(self, id, displayof=0):
  763.         """Return the pathname of the widget given by ID."""
  764.         args = ('winfo', 'pathname') \
  765.                + self._displayof(displayof) + (id,)
  766.         return self.tk.call(args)
  767.     def winfo_pixels(self, number):
  768.         """Rounded integer value of winfo_fpixels."""
  769.         return getint(
  770.             self.tk.call('winfo', 'pixels', self._w, number))
  771.     def winfo_pointerx(self):
  772.         """Return the x coordinate of the pointer on the root window."""
  773.         return getint(
  774.             self.tk.call('winfo', 'pointerx', self._w))
  775.     def winfo_pointerxy(self):
  776.         """Return a tuple of x and y coordinates of the pointer on the root window."""
  777.         return self._getints(
  778.             self.tk.call('winfo', 'pointerxy', self._w))
  779.     def winfo_pointery(self):
  780.         """Return the y coordinate of the pointer on the root window."""
  781.         return getint(
  782.             self.tk.call('winfo', 'pointery', self._w))
  783.     def winfo_reqheight(self):
  784.         """Return requested height of this widget."""
  785.         return getint(
  786.             self.tk.call('winfo', 'reqheight', self._w))
  787.     def winfo_reqwidth(self):
  788.         """Return requested width of this widget."""
  789.         return getint(
  790.             self.tk.call('winfo', 'reqwidth', self._w))
  791.     def winfo_rgb(self, color):
  792.         """Return tuple of decimal values for red, green, blue for
  793.         COLOR in this widget."""
  794.         return self._getints(
  795.             self.tk.call('winfo', 'rgb', self._w, color))
  796.     def winfo_rootx(self):
  797.         """Return x coordinate of upper left corner of this widget on the
  798.         root window."""
  799.         return getint(
  800.             self.tk.call('winfo', 'rootx', self._w))
  801.     def winfo_rooty(self):
  802.         """Return y coordinate of upper left corner of this widget on the
  803.         root window."""
  804.         return getint(
  805.             self.tk.call('winfo', 'rooty', self._w))
  806.     def winfo_screen(self):
  807.         """Return the screen name of this widget."""
  808.         return self.tk.call('winfo', 'screen', self._w)
  809.     def winfo_screencells(self):
  810.         """Return the number of the cells in the colormap of the screen
  811.         of this widget."""
  812.         return getint(
  813.             self.tk.call('winfo', 'screencells', self._w))
  814.     def winfo_screendepth(self):
  815.         """Return the number of bits per pixel of the root window of the
  816.         screen of this widget."""
  817.         return getint(
  818.             self.tk.call('winfo', 'screendepth', self._w))
  819.     def winfo_screenheight(self):
  820.         """Return the number of pixels of the height of the screen of this widget
  821.         in pixel."""
  822.         return getint(
  823.             self.tk.call('winfo', 'screenheight', self._w))
  824.     def winfo_screenmmheight(self):
  825.         """Return the number of pixels of the height of the screen of
  826.         this widget in mm."""
  827.         return getint(
  828.             self.tk.call('winfo', 'screenmmheight', self._w))
  829.     def winfo_screenmmwidth(self):
  830.         """Return the number of pixels of the width of the screen of
  831.         this widget in mm."""
  832.         return getint(
  833.             self.tk.call('winfo', 'screenmmwidth', self._w))
  834.     def winfo_screenvisual(self):
  835.         """Return one of the strings directcolor, grayscale, pseudocolor,
  836.         staticcolor, staticgray, or truecolor for the default
  837.         colormodel of this screen."""
  838.         return self.tk.call('winfo', 'screenvisual', self._w)
  839.     def winfo_screenwidth(self):
  840.         """Return the number of pixels of the width of the screen of
  841.         this widget in pixel."""
  842.         return getint(
  843.             self.tk.call('winfo', 'screenwidth', self._w))
  844.     def winfo_server(self):
  845.         """Return information of the X-Server of the screen of this widget in
  846.         the form "XmajorRminor vendor vendorVersion"."""
  847.         return self.tk.call('winfo', 'server', self._w)
  848.     def winfo_toplevel(self):
  849.         """Return the toplevel widget of this widget."""
  850.         return self._nametowidget(self.tk.call(
  851.             'winfo', 'toplevel', self._w))
  852.     def winfo_viewable(self):
  853.         """Return true if the widget and all its higher ancestors are mapped."""
  854.         return getint(
  855.             self.tk.call('winfo', 'viewable', self._w))
  856.     def winfo_visual(self):
  857.         """Return one of the strings directcolor, grayscale, pseudocolor,
  858.         staticcolor, staticgray, or truecolor for the
  859.         colormodel of this widget."""
  860.         return self.tk.call('winfo', 'visual', self._w)
  861.     def winfo_visualid(self):
  862.         """Return the X identifier for the visual for this widget."""
  863.         return self.tk.call('winfo', 'visualid', self._w)
  864.     def winfo_visualsavailable(self, includeids=0):
  865.         """Return a list of all visuals available for the screen
  866.         of this widget.
  867.  
  868.         Each item in the list consists of a visual name (see winfo_visual), a
  869.         depth and if INCLUDEIDS=1 is given also the X identifier."""
  870.         data = self.tk.split(
  871.             self.tk.call('winfo', 'visualsavailable', self._w,
  872.                      includeids and 'includeids' or None))
  873.         if type(data) is StringType:
  874.             data = [self.tk.split(data)]
  875.         return map(self.__winfo_parseitem, data)
  876.     def __winfo_parseitem(self, t):
  877.         """Internal function."""
  878.         return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
  879.     def __winfo_getint(self, x):
  880.         """Internal function."""
  881.         return int(x, 0)
  882.     def winfo_vrootheight(self):
  883.         """Return the height of the virtual root window associated with this
  884.         widget in pixels. If there is no virtual root window return the
  885.         height of the screen."""
  886.         return getint(
  887.             self.tk.call('winfo', 'vrootheight', self._w))
  888.     def winfo_vrootwidth(self):
  889.         """Return the width of the virtual root window associated with this
  890.         widget in pixel. If there is no virtual root window return the
  891.         width of the screen."""
  892.         return getint(
  893.             self.tk.call('winfo', 'vrootwidth', self._w))
  894.     def winfo_vrootx(self):
  895.         """Return the x offset of the virtual root relative to the root
  896.         window of the screen of this widget."""
  897.         return getint(
  898.             self.tk.call('winfo', 'vrootx', self._w))
  899.     def winfo_vrooty(self):
  900.         """Return the y offset of the virtual root relative to the root
  901.         window of the screen of this widget."""
  902.         return getint(
  903.             self.tk.call('winfo', 'vrooty', self._w))
  904.     def winfo_width(self):
  905.         """Return the width of this widget."""
  906.         return getint(
  907.             self.tk.call('winfo', 'width', self._w))
  908.     def winfo_x(self):
  909.         """Return the x coordinate of the upper left corner of this widget
  910.         in the parent."""
  911.         return getint(
  912.             self.tk.call('winfo', 'x', self._w))
  913.     def winfo_y(self):
  914.         """Return the y coordinate of the upper left corner of this widget
  915.         in the parent."""
  916.         return getint(
  917.             self.tk.call('winfo', 'y', self._w))
  918.     def update(self):
  919.         """Enter event loop until all pending events have been processed by Tcl."""
  920.         self.tk.call('update')
  921.     def update_idletasks(self):
  922.         """Enter event loop until all idle callbacks have been called. This
  923.         will update the display of windows but not process events caused by
  924.         the user."""
  925.         self.tk.call('update', 'idletasks')
  926.     def bindtags(self, tagList=None):
  927.         """Set or get the list of bindtags for this widget.
  928.  
  929.         With no argument return the list of all bindtags associated with
  930.         this widget. With a list of strings as argument the bindtags are
  931.         set to this list. The bindtags determine in which order events are
  932.         processed (see bind)."""
  933.         if tagList is None:
  934.             return self.tk.splitlist(
  935.                 self.tk.call('bindtags', self._w))
  936.         else:
  937.             self.tk.call('bindtags', self._w, tagList)
  938.     def _bind(self, what, sequence, func, add, needcleanup=1):
  939.         """Internal function."""
  940.         if type(func) is StringType:
  941.             self.tk.call(what + (sequence, func))
  942.         elif func:
  943.             funcid = self._register(func, self._substitute,
  944.                         needcleanup)
  945.             cmd = ('%sif {"[%s %s]" == "break"} break\n'
  946.                    %
  947.                    (add and '+' or '',
  948.                 funcid, self._subst_format_str))
  949.             self.tk.call(what + (sequence, cmd))
  950.             return funcid
  951.         elif sequence:
  952.             return self.tk.call(what + (sequence,))
  953.         else:
  954.             return self.tk.splitlist(self.tk.call(what))
  955.     def bind(self, sequence=None, func=None, add=None):
  956.         """Bind to this widget at event SEQUENCE a call to function FUNC.
  957.  
  958.         SEQUENCE is a string of concatenated event
  959.         patterns. An event pattern is of the form
  960.         <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
  961.         of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
  962.         Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
  963.         B3, Alt, Button4, B4, Double, Button5, B5 Triple,
  964.         Mod1, M1. TYPE is one of Activate, Enter, Map,
  965.         ButtonPress, Button, Expose, Motion, ButtonRelease
  966.         FocusIn, MouseWheel, Circulate, FocusOut, Property,
  967.         Colormap, Gravity Reparent, Configure, KeyPress, Key,
  968.         Unmap, Deactivate, KeyRelease Visibility, Destroy,
  969.         Leave and DETAIL is the button number for ButtonPress,
  970.         ButtonRelease and DETAIL is the Keysym for KeyPress and
  971.         KeyRelease. Examples are
  972.         <Control-Button-1> for pressing Control and mouse button 1 or
  973.         <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
  974.         An event pattern can also be a virtual event of the form
  975.         <<AString>> where AString can be arbitrary. This
  976.         event can be generated by event_generate.
  977.         If events are concatenated they must appear shortly
  978.         after each other.
  979.  
  980.         FUNC will be called if the event sequence occurs with an
  981.         instance of Event as argument. If the return value of FUNC is
  982.         "break" no further bound function is invoked.
  983.  
  984.         An additional boolean parameter ADD specifies whether FUNC will
  985.         be called additionally to the other bound function or whether
  986.         it will replace the previous function.
  987.  
  988.         Bind will return an identifier to allow deletion of the bound function with
  989.         unbind without memory leak.
  990.  
  991.         If FUNC or SEQUENCE is omitted the bound function or list
  992.         of bound events are returned."""
  993.  
  994.         return self._bind(('bind', self._w), sequence, func, add)
  995.     def unbind(self, sequence, funcid=None):
  996.         """Unbind for this widget for event SEQUENCE  the
  997.         function identified with FUNCID."""
  998.         self.tk.call('bind', self._w, sequence, '')
  999.         if funcid:
  1000.             self.deletecommand(funcid)
  1001.     def bind_all(self, sequence=None, func=None, add=None):
  1002.         """Bind to all widgets at an event SEQUENCE a call to function FUNC.
  1003.         An additional boolean parameter ADD specifies whether FUNC will
  1004.         be called additionally to the other bound function or whether
  1005.         it will replace the previous function. See bind for the return value."""
  1006.         return self._bind(('bind', 'all'), sequence, func, add, 0)
  1007.     def unbind_all(self, sequence):
  1008.         """Unbind for all widgets for event SEQUENCE all functions."""
  1009.         self.tk.call('bind', 'all' , sequence, '')
  1010.     def bind_class(self, className, sequence=None, func=None, add=None):
  1011.  
  1012.         """Bind to widgets with bindtag CLASSNAME at event
  1013.         SEQUENCE a call of function FUNC. An additional
  1014.         boolean parameter ADD specifies whether FUNC will be
  1015.         called additionally to the other bound function or
  1016.         whether it will replace the previous function. See bind for
  1017.         the return value."""
  1018.  
  1019.         return self._bind(('bind', className), sequence, func, add, 0)
  1020.     def unbind_class(self, className, sequence):
  1021.         """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
  1022.         all functions."""
  1023.         self.tk.call('bind', className , sequence, '')
  1024.     def mainloop(self, n=0):
  1025.         """Call the mainloop of Tk."""
  1026.         self.tk.mainloop(n)
  1027.     def quit(self):
  1028.         """Quit the Tcl interpreter. All widgets will be destroyed."""
  1029.         self.tk.quit()
  1030.     def _getints(self, string):
  1031.         """Internal function."""
  1032.         if string:
  1033.             return tuple(map(getint, self.tk.splitlist(string)))
  1034.     def _getdoubles(self, string):
  1035.         """Internal function."""
  1036.         if string:
  1037.             return tuple(map(getdouble, self.tk.splitlist(string)))
  1038.     def _getboolean(self, string):
  1039.         """Internal function."""
  1040.         if string:
  1041.             return self.tk.getboolean(string)
  1042.     def _displayof(self, displayof):
  1043.         """Internal function."""
  1044.         if displayof:
  1045.             return ('-displayof', displayof)
  1046.         if displayof is None:
  1047.             return ('-displayof', self._w)
  1048.         return ()
  1049.     def _options(self, cnf, kw = None):
  1050.         """Internal function."""
  1051.         if kw:
  1052.             cnf = _cnfmerge((cnf, kw))
  1053.         else:
  1054.             cnf = _cnfmerge(cnf)
  1055.         res = ()
  1056.         for k, v in cnf.items():
  1057.             if v is not None:
  1058.                 if k[-1] == '_': k = k[:-1]
  1059.                 if callable(v):
  1060.                     v = self._register(v)
  1061.                 res = res + ('-'+k, v)
  1062.         return res
  1063.     def nametowidget(self, name):
  1064.         """Return the Tkinter instance of a widget identified by
  1065.         its Tcl name NAME."""
  1066.         w = self
  1067.         if name[0] == '.':
  1068.             w = w._root()
  1069.             name = name[1:]
  1070.         while name:
  1071.             i = name.find('.')
  1072.             if i >= 0:
  1073.                 name, tail = name[:i], name[i+1:]
  1074.             else:
  1075.                 tail = ''
  1076.             w = w.children[name]
  1077.             name = tail
  1078.         return w
  1079.     _nametowidget = nametowidget
  1080.     def _register(self, func, subst=None, needcleanup=1):
  1081.         """Return a newly created Tcl function. If this
  1082.         function is called, the Python function FUNC will
  1083.         be executed. An optional function SUBST can
  1084.         be given which will be executed before FUNC."""
  1085.         f = CallWrapper(func, subst, self).__call__
  1086.         name = repr(id(f))
  1087.         try:
  1088.             func = func.im_func
  1089.         except AttributeError:
  1090.             pass
  1091.         try:
  1092.             name = name + func.__name__
  1093.         except AttributeError:
  1094.             pass
  1095.         self.tk.createcommand(name, f)
  1096.         if needcleanup:
  1097.             if self._tclCommands is None:
  1098.                 self._tclCommands = []
  1099.             self._tclCommands.append(name)
  1100.         #print '+ Tkinter created command', name
  1101.         return name
  1102.     register = _register
  1103.     def _root(self):
  1104.         """Internal function."""
  1105.         w = self
  1106.         while w.master: w = w.master
  1107.         return w
  1108.     _subst_format = ('%#', '%b', '%f', '%h', '%k',
  1109.              '%s', '%t', '%w', '%x', '%y',
  1110.              '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
  1111.     _subst_format_str = " ".join(_subst_format)
  1112.     def _substitute(self, *args):
  1113.         """Internal function."""
  1114.         if len(args) != len(self._subst_format): return args
  1115.         getboolean = self.tk.getboolean
  1116.  
  1117.         getint = int
  1118.         def getint_event(s):
  1119.             """Tk changed behavior in 8.4.2, returning "??" rather more often."""
  1120.             try:
  1121.                 return int(s)
  1122.             except ValueError:
  1123.                 return s
  1124.  
  1125.         nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
  1126.         # Missing: (a, c, d, m, o, v, B, R)
  1127.         e = Event()
  1128.         # serial field: valid vor all events
  1129.         # number of button: ButtonPress and ButtonRelease events only
  1130.         # height field: Configure, ConfigureRequest, Create,
  1131.         # ResizeRequest, and Expose events only
  1132.         # keycode field: KeyPress and KeyRelease events only
  1133.         # time field: "valid for events that contain a time field"
  1134.         # width field: Configure, ConfigureRequest, Create, ResizeRequest,
  1135.         # and Expose events only
  1136.         # x field: "valid for events that contain a x field"
  1137.         # y field: "valid for events that contain a y field"
  1138.         # keysym as decimal: KeyPress and KeyRelease events only
  1139.         # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
  1140.         # KeyRelease,and Motion events
  1141.         e.serial = getint(nsign)
  1142.         e.num = getint_event(b)
  1143.         try: e.focus = getboolean(f)
  1144.         except TclError: pass
  1145.         e.height = getint_event(h)
  1146.         e.keycode = getint_event(k)
  1147.         e.state = getint_event(s)
  1148.         e.time = getint_event(t)
  1149.         e.width = getint_event(w)
  1150.         e.x = getint_event(x)
  1151.         e.y = getint_event(y)
  1152.         e.char = A
  1153.         try: e.send_event = getboolean(E)
  1154.         except TclError: pass
  1155.         e.keysym = K
  1156.         e.keysym_num = getint_event(N)
  1157.         e.type = T
  1158.         try:
  1159.             e.widget = self._nametowidget(W)
  1160.         except KeyError:
  1161.             e.widget = W
  1162.         e.x_root = getint_event(X)
  1163.         e.y_root = getint_event(Y)
  1164.         try:
  1165.             e.delta = getint(D)
  1166.         except ValueError:
  1167.             e.delta = 0
  1168.         return (e,)
  1169.     def _report_exception(self):
  1170.         """Internal function."""
  1171.         import sys
  1172.         exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
  1173.         root = self._root()
  1174.         root.report_callback_exception(exc, val, tb)
  1175.     def _configure(self, cmd, cnf, kw):
  1176.         """Internal function."""
  1177.         if kw:
  1178.             cnf = _cnfmerge((cnf, kw))
  1179.         elif cnf:
  1180.             cnf = _cnfmerge(cnf)
  1181.         if cnf is None:
  1182.             cnf = {}
  1183.             for x in self.tk.split(
  1184.                     self.tk.call(_flatten((self._w, cmd)))):
  1185.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1186.             return cnf
  1187.         if type(cnf) is StringType:
  1188.             x = self.tk.split(
  1189.                     self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
  1190.             return (x[0][1:],) + x[1:]
  1191.         self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
  1192.     # These used to be defined in Widget:
  1193.     def configure(self, cnf=None, **kw):
  1194.         """Configure resources of a widget.
  1195.  
  1196.         The values for resources are specified as keyword
  1197.         arguments. To get an overview about
  1198.         the allowed keyword arguments call the method keys.
  1199.         """
  1200.         return self._configure('configure', cnf, kw)
  1201.     config = configure
  1202.     def cget(self, key):
  1203.         """Return the resource value for a KEY given as string."""
  1204.         return self.tk.call(self._w, 'cget', '-' + key)
  1205.     __getitem__ = cget
  1206.     def __setitem__(self, key, value):
  1207.         self.configure({key: value})
  1208.     def keys(self):
  1209.         """Return a list of all resource names of this widget."""
  1210.         return map(lambda x: x[0][1:],
  1211.                self.tk.split(self.tk.call(self._w, 'configure')))
  1212.     def __str__(self):
  1213.         """Return the window path name of this widget."""
  1214.         return self._w
  1215.     # Pack methods that apply to the master
  1216.     _noarg_ = ['_noarg_']
  1217.     def pack_propagate(self, flag=_noarg_):
  1218.         """Set or get the status for propagation of geometry information.
  1219.  
  1220.         A boolean argument specifies whether the geometry information
  1221.         of the slaves will determine the size of this widget. If no argument
  1222.         is given the current setting will be returned.
  1223.         """
  1224.         if flag is Misc._noarg_:
  1225.             return self._getboolean(self.tk.call(
  1226.                 'pack', 'propagate', self._w))
  1227.         else:
  1228.             self.tk.call('pack', 'propagate', self._w, flag)
  1229.     propagate = pack_propagate
  1230.     def pack_slaves(self):
  1231.         """Return a list of all slaves of this widget
  1232.         in its packing order."""
  1233.         return map(self._nametowidget,
  1234.                self.tk.splitlist(
  1235.                    self.tk.call('pack', 'slaves', self._w)))
  1236.     slaves = pack_slaves
  1237.     # Place method that applies to the master
  1238.     def place_slaves(self):
  1239.         """Return a list of all slaves of this widget
  1240.         in its packing order."""
  1241.         return map(self._nametowidget,
  1242.                self.tk.splitlist(
  1243.                    self.tk.call(
  1244.                        'place', 'slaves', self._w)))
  1245.     # Grid methods that apply to the master
  1246.     def grid_bbox(self, column=None, row=None, col2=None, row2=None):
  1247.         """Return a tuple of integer coordinates for the bounding
  1248.         box of this widget controlled by the geometry manager grid.
  1249.  
  1250.         If COLUMN, ROW is given the bounding box applies from
  1251.         the cell with row and column 0 to the specified
  1252.         cell. If COL2 and ROW2 are given the bounding box
  1253.         starts at that cell.
  1254.  
  1255.         The returned integers specify the offset of the upper left
  1256.         corner in the master widget and the width and height.
  1257.         """
  1258.         args = ('grid', 'bbox', self._w)
  1259.         if column is not None and row is not None:
  1260.             args = args + (column, row)
  1261.         if col2 is not None and row2 is not None:
  1262.             args = args + (col2, row2)
  1263.         return self._getints(self.tk.call(*args)) or None
  1264.  
  1265.     bbox = grid_bbox
  1266.     def _grid_configure(self, command, index, cnf, kw):
  1267.         """Internal function."""
  1268.         if type(cnf) is StringType and not kw:
  1269.             if cnf[-1:] == '_':
  1270.                 cnf = cnf[:-1]
  1271.             if cnf[:1] != '-':
  1272.                 cnf = '-'+cnf
  1273.             options = (cnf,)
  1274.         else:
  1275.             options = self._options(cnf, kw)
  1276.         if not options:
  1277.             res = self.tk.call('grid',
  1278.                        command, self._w, index)
  1279.             words = self.tk.splitlist(res)
  1280.             dict = {}
  1281.             for i in range(0, len(words), 2):
  1282.                 key = words[i][1:]
  1283.                 value = words[i+1]
  1284.                 if not value:
  1285.                     value = None
  1286.                 elif '.' in value:
  1287.                     value = getdouble(value)
  1288.                 else:
  1289.                     value = getint(value)
  1290.                 dict[key] = value
  1291.             return dict
  1292.         res = self.tk.call(
  1293.                   ('grid', command, self._w, index)
  1294.                   + options)
  1295.         if len(options) == 1:
  1296.             if not res: return None
  1297.             # In Tk 7.5, -width can be a float
  1298.             if '.' in res: return getdouble(res)
  1299.             return getint(res)
  1300.     def grid_columnconfigure(self, index, cnf={}, **kw):
  1301.         """Configure column INDEX of a grid.
  1302.  
  1303.         Valid resources are minsize (minimum size of the column),
  1304.         weight (how much does additional space propagate to this column)
  1305.         and pad (how much space to let additionally)."""
  1306.         return self._grid_configure('columnconfigure', index, cnf, kw)
  1307.     columnconfigure = grid_columnconfigure
  1308.     def grid_location(self, x, y):
  1309.         """Return a tuple of column and row which identify the cell
  1310.         at which the pixel at position X and Y inside the master
  1311.         widget is located."""
  1312.         return self._getints(
  1313.             self.tk.call(
  1314.                 'grid', 'location', self._w, x, y)) or None
  1315.     def grid_propagate(self, flag=_noarg_):
  1316.         """Set or get the status for propagation of geometry information.
  1317.  
  1318.         A boolean argument specifies whether the geometry information
  1319.         of the slaves will determine the size of this widget. If no argument
  1320.         is given, the current setting will be returned.
  1321.         """
  1322.         if flag is Misc._noarg_:
  1323.             return self._getboolean(self.tk.call(
  1324.                 'grid', 'propagate', self._w))
  1325.         else:
  1326.             self.tk.call('grid', 'propagate', self._w, flag)
  1327.     def grid_rowconfigure(self, index, cnf={}, **kw):
  1328.         """Configure row INDEX of a grid.
  1329.  
  1330.         Valid resources are minsize (minimum size of the row),
  1331.         weight (how much does additional space propagate to this row)
  1332.         and pad (how much space to let additionally)."""
  1333.         return self._grid_configure('rowconfigure', index, cnf, kw)
  1334.     rowconfigure = grid_rowconfigure
  1335.     def grid_size(self):
  1336.         """Return a tuple of the number of column and rows in the grid."""
  1337.         return self._getints(
  1338.             self.tk.call('grid', 'size', self._w)) or None
  1339.     size = grid_size
  1340.     def grid_slaves(self, row=None, column=None):
  1341.         """Return a list of all slaves of this widget
  1342.         in its packing order."""
  1343.         args = ()
  1344.         if row is not None:
  1345.             args = args + ('-row', row)
  1346.         if column is not None:
  1347.             args = args + ('-column', column)
  1348.         return map(self._nametowidget,
  1349.                self.tk.splitlist(self.tk.call(
  1350.                    ('grid', 'slaves', self._w) + args)))
  1351.  
  1352.     # Support for the "event" command, new in Tk 4.2.
  1353.     # By Case Roole.
  1354.  
  1355.     def event_add(self, virtual, *sequences):
  1356.         """Bind a virtual event VIRTUAL (of the form <<Name>>)
  1357.         to an event SEQUENCE such that the virtual event is triggered
  1358.         whenever SEQUENCE occurs."""
  1359.         args = ('event', 'add', virtual) + sequences
  1360.         self.tk.call(args)
  1361.  
  1362.     def event_delete(self, virtual, *sequences):
  1363.         """Unbind a virtual event VIRTUAL from SEQUENCE."""
  1364.         args = ('event', 'delete', virtual) + sequences
  1365.         self.tk.call(args)
  1366.  
  1367.     def event_generate(self, sequence, **kw):
  1368.         """Generate an event SEQUENCE. Additional
  1369.         keyword arguments specify parameter of the event
  1370.         (e.g. x, y, rootx, rooty)."""
  1371.         args = ('event', 'generate', self._w, sequence)
  1372.         for k, v in kw.items():
  1373.             args = args + ('-%s' % k, str(v))
  1374.         self.tk.call(args)
  1375.  
  1376.     def event_info(self, virtual=None):
  1377.         """Return a list of all virtual events or the information
  1378.         about the SEQUENCE bound to the virtual event VIRTUAL."""
  1379.         return self.tk.splitlist(
  1380.             self.tk.call('event', 'info', virtual))
  1381.  
  1382.     # Image related commands
  1383.  
  1384.     def image_names(self):
  1385.         """Return a list of all existing image names."""
  1386.         return self.tk.call('image', 'names')
  1387.  
  1388.     def image_types(self):
  1389.         """Return a list of all available image types (e.g. phote bitmap)."""
  1390.         return self.tk.call('image', 'types')
  1391.  
  1392.  
  1393. class CallWrapper:
  1394.     """Internal class. Stores function to call when some user
  1395.     defined Tcl function is called e.g. after an event occurred."""
  1396.     def __init__(self, func, subst, widget):
  1397.         """Store FUNC, SUBST and WIDGET as members."""
  1398.         self.func = func
  1399.         self.subst = subst
  1400.         self.widget = widget
  1401.     def __call__(self, *args):
  1402.         """Apply first function SUBST to arguments, than FUNC."""
  1403.         try:
  1404.             if self.subst:
  1405.                 args = self.subst(*args)
  1406.             return self.func(*args)
  1407.         except SystemExit, msg:
  1408.             raise SystemExit, msg
  1409.         except:
  1410.             self.widget._report_exception()
  1411.  
  1412.  
  1413. class Wm:
  1414.     """Provides functions for the communication with the window manager."""
  1415.  
  1416.     def wm_aspect(self,
  1417.               minNumer=None, minDenom=None,
  1418.               maxNumer=None, maxDenom=None):
  1419.         """Instruct the window manager to set the aspect ratio (width/height)
  1420.         of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
  1421.         of the actual values if no argument is given."""
  1422.         return self._getints(
  1423.             self.tk.call('wm', 'aspect', self._w,
  1424.                      minNumer, minDenom,
  1425.                      maxNumer, maxDenom))
  1426.     aspect = wm_aspect
  1427.  
  1428.     def wm_attributes(self, *args):
  1429.         """This subcommand returns or sets platform specific attributes
  1430.  
  1431.         The first form returns a list of the platform specific flags and
  1432.         their values. The second form returns the value for the specific
  1433.         option. The third form sets one or more of the values. The values
  1434.         are as follows:
  1435.  
  1436.         On Windows, -disabled gets or sets whether the window is in a
  1437.         disabled state. -toolwindow gets or sets the style of the window
  1438.         to toolwindow (as defined in the MSDN). -topmost gets or sets
  1439.         whether this is a topmost window (displays above all other
  1440.         windows).
  1441.  
  1442.         On Macintosh, XXXXX
  1443.  
  1444.         On Unix, there are currently no special attribute values.
  1445.         """
  1446.         args = ('wm', 'attributes', self._w) + args
  1447.         return self.tk.call(args)
  1448.     attributes=wm_attributes
  1449.  
  1450.     def wm_client(self, name=None):
  1451.         """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
  1452.         current value."""
  1453.         return self.tk.call('wm', 'client', self._w, name)
  1454.     client = wm_client
  1455.     def wm_colormapwindows(self, *wlist):
  1456.         """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
  1457.         of this widget. This list contains windows whose colormaps differ from their
  1458.         parents. Return current list of widgets if WLIST is empty."""
  1459.         if len(wlist) > 1:
  1460.             wlist = (wlist,) # Tk needs a list of windows here
  1461.         args = ('wm', 'colormapwindows', self._w) + wlist
  1462.         return map(self._nametowidget, self.tk.call(args))
  1463.     colormapwindows = wm_colormapwindows
  1464.     def wm_command(self, value=None):
  1465.         """Store VALUE in WM_COMMAND property. It is the command
  1466.         which shall be used to invoke the application. Return current
  1467.         command if VALUE is None."""
  1468.         return self.tk.call('wm', 'command', self._w, value)
  1469.     command = wm_command
  1470.     def wm_deiconify(self):
  1471.         """Deiconify this widget. If it was never mapped it will not be mapped.
  1472.         On Windows it will raise this widget and give it the focus."""
  1473.         return self.tk.call('wm', 'deiconify', self._w)
  1474.     deiconify = wm_deiconify
  1475.     def wm_focusmodel(self, model=None):
  1476.         """Set focus model to MODEL. "active" means that this widget will claim
  1477.         the focus itself, "passive" means that the window manager shall give
  1478.         the focus. Return current focus model if MODEL is None."""
  1479.         return self.tk.call('wm', 'focusmodel', self._w, model)
  1480.     focusmodel = wm_focusmodel
  1481.     def wm_frame(self):
  1482.         """Return identifier for decorative frame of this widget if present."""
  1483.         return self.tk.call('wm', 'frame', self._w)
  1484.     frame = wm_frame
  1485.     def wm_geometry(self, newGeometry=None):
  1486.         """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
  1487.         current value if None is given."""
  1488.         return self.tk.call('wm', 'geometry', self._w, newGeometry)
  1489.     geometry = wm_geometry
  1490.     def wm_grid(self,
  1491.          baseWidth=None, baseHeight=None,
  1492.          widthInc=None, heightInc=None):
  1493.         """Instruct the window manager that this widget shall only be
  1494.         resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
  1495.         height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
  1496.         number of grid units requested in Tk_GeometryRequest."""
  1497.         return self._getints(self.tk.call(
  1498.             'wm', 'grid', self._w,
  1499.             baseWidth, baseHeight, widthInc, heightInc))
  1500.     grid = wm_grid
  1501.     def wm_group(self, pathName=None):
  1502.         """Set the group leader widgets for related widgets to PATHNAME. Return
  1503.         the group leader of this widget if None is given."""
  1504.         return self.tk.call('wm', 'group', self._w, pathName)
  1505.     group = wm_group
  1506.     def wm_iconbitmap(self, bitmap=None, default=None):
  1507.         """Set bitmap for the iconified widget to BITMAP. Return
  1508.         the bitmap if None is given.
  1509.  
  1510.         Under Windows, the DEFAULT parameter can be used to set the icon
  1511.         for the widget and any descendents that don't have an icon set
  1512.         explicitly.  DEFAULT can be the relative path to a .ico file
  1513.         (example: root.iconbitmap(default='myicon.ico') ).  See Tk
  1514.         documentation for more information."""
  1515.         if default:
  1516.             return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
  1517.         else:
  1518.             return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  1519.     iconbitmap = wm_iconbitmap
  1520.     def wm_iconify(self):
  1521.         """Display widget as icon."""
  1522.         return self.tk.call('wm', 'iconify', self._w)
  1523.     iconify = wm_iconify
  1524.     def wm_iconmask(self, bitmap=None):
  1525.         """Set mask for the icon bitmap of this widget. Return the
  1526.         mask if None is given."""
  1527.         return self.tk.call('wm', 'iconmask', self._w, bitmap)
  1528.     iconmask = wm_iconmask
  1529.     def wm_iconname(self, newName=None):
  1530.         """Set the name of the icon for this widget. Return the name if
  1531.         None is given."""
  1532.         return self.tk.call('wm', 'iconname', self._w, newName)
  1533.     iconname = wm_iconname
  1534.     def wm_iconposition(self, x=None, y=None):
  1535.         """Set the position of the icon of this widget to X and Y. Return
  1536.         a tuple of the current values of X and X if None is given."""
  1537.         return self._getints(self.tk.call(
  1538.             'wm', 'iconposition', self._w, x, y))
  1539.     iconposition = wm_iconposition
  1540.     def wm_iconwindow(self, pathName=None):
  1541.         """Set widget PATHNAME to be displayed instead of icon. Return the current
  1542.         value if None is given."""
  1543.         return self.tk.call('wm', 'iconwindow', self._w, pathName)
  1544.     iconwindow = wm_iconwindow
  1545.     def wm_maxsize(self, width=None, height=None):
  1546.         """Set max WIDTH and HEIGHT for this widget. If the window is gridded
  1547.         the values are given in grid units. Return the current values if None
  1548.         is given."""
  1549.         return self._getints(self.tk.call(
  1550.             'wm', 'maxsize', self._w, width, height))
  1551.     maxsize = wm_maxsize
  1552.     def wm_minsize(self, width=None, height=None):
  1553.         """Set min WIDTH and HEIGHT for this widget. If the window is gridded
  1554.         the values are given in grid units. Return the current values if None
  1555.         is given."""
  1556.         return self._getints(self.tk.call(
  1557.             'wm', 'minsize', self._w, width, height))
  1558.     minsize = wm_minsize
  1559.     def wm_overrideredirect(self, boolean=None):
  1560.         """Instruct the window manager to ignore this widget
  1561.         if BOOLEAN is given with 1. Return the current value if None
  1562.         is given."""
  1563.         return self._getboolean(self.tk.call(
  1564.             'wm', 'overrideredirect', self._w, boolean))
  1565.     overrideredirect = wm_overrideredirect
  1566.     def wm_positionfrom(self, who=None):
  1567.         """Instruct the window manager that the position of this widget shall
  1568.         be defined by the user if WHO is "user", and by its own policy if WHO is
  1569.         "program"."""
  1570.         return self.tk.call('wm', 'positionfrom', self._w, who)
  1571.     positionfrom = wm_positionfrom
  1572.     def wm_protocol(self, name=None, func=None):
  1573.         """Bind function FUNC to command NAME for this widget.
  1574.         Return the function bound to NAME if None is given. NAME could be
  1575.         e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
  1576.         if callable(func):
  1577.             command = self._register(func)
  1578.         else:
  1579.             command = func
  1580.         return self.tk.call(
  1581.             'wm', 'protocol', self._w, name, command)
  1582.     protocol = wm_protocol
  1583.     def wm_resizable(self, width=None, height=None):
  1584.         """Instruct the window manager whether this width can be resized
  1585.         in WIDTH or HEIGHT. Both values are boolean values."""
  1586.         return self.tk.call('wm', 'resizable', self._w, width, height)
  1587.     resizable = wm_resizable
  1588.     def wm_sizefrom(self, who=None):
  1589.         """Instruct the window manager that the size of this widget shall
  1590.         be defined by the user if WHO is "user", and by its own policy if WHO is
  1591.         "program"."""
  1592.         return self.tk.call('wm', 'sizefrom', self._w, who)
  1593.     sizefrom = wm_sizefrom
  1594.     def wm_state(self, newstate=None):
  1595.         """Query or set the state of this widget as one of normal, icon,
  1596.         iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
  1597.         return self.tk.call('wm', 'state', self._w, newstate)
  1598.     state = wm_state
  1599.     def wm_title(self, string=None):
  1600.         """Set the title of this widget."""
  1601.         return self.tk.call('wm', 'title', self._w, string)
  1602.     title = wm_title
  1603.     def wm_transient(self, master=None):
  1604.         """Instruct the window manager that this widget is transient
  1605.         with regard to widget MASTER."""
  1606.         return self.tk.call('wm', 'transient', self._w, master)
  1607.     transient = wm_transient
  1608.     def wm_withdraw(self):
  1609.         """Withdraw this widget from the screen such that it is unmapped
  1610.         and forgotten by the window manager. Re-draw it with wm_deiconify."""
  1611.         return self.tk.call('wm', 'withdraw', self._w)
  1612.     withdraw = wm_withdraw
  1613.  
  1614.  
  1615. class Tk(Misc, Wm):
  1616.     """Toplevel widget of Tk which represents mostly the main window
  1617.     of an appliation. It has an associated Tcl interpreter."""
  1618.     _w = '.'
  1619.     def __init__(self, screenName=None, baseName=None, className='Tk',
  1620.                  useTk=1, sync=0, use=None):
  1621.         """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
  1622.         be created. BASENAME will be used for the identification of the profile file (see
  1623.         readprofile).
  1624.         It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
  1625.         is the name of the widget class."""
  1626.         self.master = None
  1627.         self.children = {}
  1628.         self._tkloaded = 0
  1629.         # to avoid recursions in the getattr code in case of failure, we
  1630.         # ensure that self.tk is always _something_.
  1631.         self.tk = None
  1632.         if baseName is None:
  1633.             import sys, os
  1634.             baseName = os.path.basename(sys.argv[0])
  1635.             baseName, ext = os.path.splitext(baseName)
  1636.             if ext not in ('.py', '.pyc', '.pyo'):
  1637.                 baseName = baseName + ext
  1638.         interactive = 0
  1639.         self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
  1640.         if useTk:
  1641.             self._loadtk()
  1642.         self.readprofile(baseName, className)
  1643.     def loadtk(self):
  1644.         if not self._tkloaded:
  1645.             self.tk.loadtk()
  1646.             self._loadtk()
  1647.     def _loadtk(self):
  1648.         self._tkloaded = 1
  1649.         global _default_root
  1650.         if _MacOS and hasattr(_MacOS, 'SchedParams'):
  1651.             # Disable event scanning except for Command-Period
  1652.             _MacOS.SchedParams(1, 0)
  1653.             # Work around nasty MacTk bug
  1654.             # XXX Is this one still needed?
  1655.             self.update()
  1656.         # Version sanity checks
  1657.         tk_version = self.tk.getvar('tk_version')
  1658.         if tk_version != _tkinter.TK_VERSION:
  1659.             raise RuntimeError, \
  1660.             "tk.h version (%s) doesn't match libtk.a version (%s)" \
  1661.             % (_tkinter.TK_VERSION, tk_version)
  1662.         # Under unknown circumstances, tcl_version gets coerced to float
  1663.         tcl_version = str(self.tk.getvar('tcl_version'))
  1664.         if tcl_version != _tkinter.TCL_VERSION:
  1665.             raise RuntimeError, \
  1666.             "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  1667.             % (_tkinter.TCL_VERSION, tcl_version)
  1668.         if TkVersion < 4.0:
  1669.             raise RuntimeError, \
  1670.             "Tk 4.0 or higher is required; found Tk %s" \
  1671.             % str(TkVersion)
  1672.         # Create and register the tkerror and exit commands
  1673.         # We need to inline parts of _register here, _ register
  1674.         # would register differently-named commands.
  1675.         if self._tclCommands is None:
  1676.             self._tclCommands = []
  1677.         self.tk.createcommand('tkerror', _tkerror)
  1678.         self.tk.createcommand('exit', _exit)
  1679.         self._tclCommands.append('tkerror')
  1680.         self._tclCommands.append('exit')
  1681.         if _support_default_root and not _default_root:
  1682.             _default_root = self
  1683.         self.protocol("WM_DELETE_WINDOW", self.destroy)
  1684.     def destroy(self):
  1685.         """Destroy this and all descendants widgets. This will
  1686.         end the application of this Tcl interpreter."""
  1687.         for c in self.children.values(): c.destroy()
  1688.         self.tk.call('destroy', self._w)
  1689.         Misc.destroy(self)
  1690.         global _default_root
  1691.         if _support_default_root and _default_root is self:
  1692.             _default_root = None
  1693.     def readprofile(self, baseName, className):
  1694.         """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
  1695.         the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
  1696.         such a file exists in the home directory."""
  1697.         import os
  1698.         if os.environ.has_key('HOME'): home = os.environ['HOME']
  1699.         else: home = os.curdir
  1700.         class_tcl = os.path.join(home, '.%s.tcl' % className)
  1701.         class_py = os.path.join(home, '.%s.py' % className)
  1702.         base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  1703.         base_py = os.path.join(home, '.%s.py' % baseName)
  1704.         dir = {'self': self}
  1705.         exec 'from Tkinter import *' in dir
  1706.         if os.path.isfile(class_tcl):
  1707.             self.tk.call('source', class_tcl)
  1708.         if os.path.isfile(class_py):
  1709.             execfile(class_py, dir)
  1710.         if os.path.isfile(base_tcl):
  1711.             self.tk.call('source', base_tcl)
  1712.         if os.path.isfile(base_py):
  1713.             execfile(base_py, dir)
  1714.     def report_callback_exception(self, exc, val, tb):
  1715.         """Internal function. It reports exception on sys.stderr."""
  1716.         import traceback, sys
  1717.         sys.stderr.write("Exception in Tkinter callback\n")
  1718.         sys.last_type = exc
  1719.         sys.last_value = val
  1720.         sys.last_traceback = tb
  1721.         traceback.print_exception(exc, val, tb)
  1722.     def __getattr__(self, attr):
  1723.         "Delegate attribute access to the interpreter object"
  1724.         return getattr(self.tk, attr)
  1725.  
  1726. # Ideally, the classes Pack, Place and Grid disappear, the
  1727. # pack/place/grid methods are defined on the Widget class, and
  1728. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  1729. # ...), with pack(), place() and grid() being short for
  1730. # pack_configure(), place_configure() and grid_columnconfigure(), and
  1731. # forget() being short for pack_forget().  As a practical matter, I'm
  1732. # afraid that there is too much code out there that may be using the
  1733. # Pack, Place or Grid class, so I leave them intact -- but only as
  1734. # backwards compatibility features.  Also note that those methods that
  1735. # take a master as argument (e.g. pack_propagate) have been moved to
  1736. # the Misc class (which now incorporates all methods common between
  1737. # toplevel and interior widgets).  Again, for compatibility, these are
  1738. # copied into the Pack, Place or Grid class.
  1739.  
  1740.  
  1741. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
  1742.     return Tk(screenName, baseName, className, useTk)
  1743.  
  1744. class Pack:
  1745.     """Geometry manager Pack.
  1746.  
  1747.     Base class to use the methods pack_* in every widget."""
  1748.     def pack_configure(self, cnf={}, **kw):
  1749.         """Pack a widget in the parent widget. Use as options:
  1750.         after=widget - pack it after you have packed widget
  1751.         anchor=NSEW (or subset) - position widget according to
  1752.                                   given direction
  1753.                 before=widget - pack it before you will pack widget
  1754.         expand=bool - expand widget if parent size grows
  1755.         fill=NONE or X or Y or BOTH - fill widget if widget grows
  1756.         in=master - use master to contain this widget
  1757.         ipadx=amount - add internal padding in x direction
  1758.         ipady=amount - add internal padding in y direction
  1759.         padx=amount - add padding in x direction
  1760.         pady=amount - add padding in y direction
  1761.         side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
  1762.         """
  1763.         self.tk.call(
  1764.               ('pack', 'configure', self._w)
  1765.               + self._options(cnf, kw))
  1766.     pack = configure = config = pack_configure
  1767.     def pack_forget(self):
  1768.         """Unmap this widget and do not use it for the packing order."""
  1769.         self.tk.call('pack', 'forget', self._w)
  1770.     forget = pack_forget
  1771.     def pack_info(self):
  1772.         """Return information about the packing options
  1773.         for this widget."""
  1774.         words = self.tk.splitlist(
  1775.             self.tk.call('pack', 'info', self._w))
  1776.         dict = {}
  1777.         for i in range(0, len(words), 2):
  1778.             key = words[i][1:]
  1779.             value = words[i+1]
  1780.             if value[:1] == '.':
  1781.                 value = self._nametowidget(value)
  1782.             dict[key] = value
  1783.         return dict
  1784.     info = pack_info
  1785.     propagate = pack_propagate = Misc.pack_propagate
  1786.     slaves = pack_slaves = Misc.pack_slaves
  1787.  
  1788. class Place:
  1789.     """Geometry manager Place.
  1790.  
  1791.     Base class to use the methods place_* in every widget."""
  1792.     def place_configure(self, cnf={}, **kw):
  1793.         """Place a widget in the parent widget. Use as options:
  1794.         in=master - master relative to which the widget is placed.
  1795.         x=amount - locate anchor of this widget at position x of master
  1796.         y=amount - locate anchor of this widget at position y of master
  1797.         relx=amount - locate anchor of this widget between 0.0 and 1.0
  1798.                       relative to width of master (1.0 is right edge)
  1799.             rely=amount - locate anchor of this widget between 0.0 and 1.0
  1800.                       relative to height of master (1.0 is bottom edge)
  1801.             anchor=NSEW (or subset) - position anchor according to given direction
  1802.         width=amount - width of this widget in pixel
  1803.         height=amount - height of this widget in pixel
  1804.         relwidth=amount - width of this widget between 0.0 and 1.0
  1805.                           relative to width of master (1.0 is the same width
  1806.                   as the master)
  1807.             relheight=amount - height of this widget between 0.0 and 1.0
  1808.                            relative to height of master (1.0 is the same
  1809.                    height as the master)
  1810.             bordermode="inside" or "outside" - whether to take border width of master widget
  1811.                                                into account
  1812.             """
  1813.         for k in ['in_']:
  1814.             if kw.has_key(k):
  1815.                 kw[k[:-1]] = kw[k]
  1816.                 del kw[k]
  1817.         self.tk.call(
  1818.               ('place', 'configure', self._w)
  1819.               + self._options(cnf, kw))
  1820.     place = configure = config = place_configure
  1821.     def place_forget(self):
  1822.         """Unmap this widget."""
  1823.         self.tk.call('place', 'forget', self._w)
  1824.     forget = place_forget
  1825.     def place_info(self):
  1826.         """Return information about the placing options
  1827.         for this widget."""
  1828.         words = self.tk.splitlist(
  1829.             self.tk.call('place', 'info', self._w))
  1830.         dict = {}
  1831.         for i in range(0, len(words), 2):
  1832.             key = words[i][1:]
  1833.             value = words[i+1]
  1834.             if value[:1] == '.':
  1835.                 value = self._nametowidget(value)
  1836.             dict[key] = value
  1837.         return dict
  1838.     info = place_info
  1839.     slaves = place_slaves = Misc.place_slaves
  1840.  
  1841. class Grid:
  1842.     """Geometry manager Grid.
  1843.  
  1844.     Base class to use the methods grid_* in every widget."""
  1845.     # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  1846.     def grid_configure(self, cnf={}, **kw):
  1847.         """Position a widget in the parent widget in a grid. Use as options:
  1848.         column=number - use cell identified with given column (starting with 0)
  1849.         columnspan=number - this widget will span several columns
  1850.         in=master - use master to contain this widget
  1851.         ipadx=amount - add internal padding in x direction
  1852.         ipady=amount - add internal padding in y direction
  1853.         padx=amount - add padding in x direction
  1854.         pady=amount - add padding in y direction
  1855.         row=number - use cell identified with given row (starting with 0)
  1856.         rowspan=number - this widget will span several rows
  1857.         sticky=NSEW - if cell is larger on which sides will this
  1858.                       widget stick to the cell boundary
  1859.         """
  1860.         self.tk.call(
  1861.               ('grid', 'configure', self._w)
  1862.               + self._options(cnf, kw))
  1863.     grid = configure = config = grid_configure
  1864.     bbox = grid_bbox = Misc.grid_bbox
  1865.     columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  1866.     def grid_forget(self):
  1867.         """Unmap this widget."""
  1868.         self.tk.call('grid', 'forget', self._w)
  1869.     forget = grid_forget
  1870.     def grid_remove(self):
  1871.         """Unmap this widget but remember the grid options."""
  1872.         self.tk.call('grid', 'remove', self._w)
  1873.     def grid_info(self):
  1874.         """Return information about the options
  1875.         for positioning this widget in a grid."""
  1876.         words = self.tk.splitlist(
  1877.             self.tk.call('grid', 'info', self._w))
  1878.         dict = {}
  1879.         for i in range(0, len(words), 2):
  1880.             key = words[i][1:]
  1881.             value = words[i+1]
  1882.             if value[:1] == '.':
  1883.                 value = self._nametowidget(value)
  1884.             dict[key] = value
  1885.         return dict
  1886.     info = grid_info
  1887.     location = grid_location = Misc.grid_location
  1888.     propagate = grid_propagate = Misc.grid_propagate
  1889.     rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  1890.     size = grid_size = Misc.grid_size
  1891.     slaves = grid_slaves = Misc.grid_slaves
  1892.  
  1893. class BaseWidget(Misc):
  1894.     """Internal class."""
  1895.     def _setup(self, master, cnf):
  1896.         """Internal function. Sets up information about children."""
  1897.         if _support_default_root:
  1898.             global _default_root
  1899.             if not master:
  1900.                 if not _default_root:
  1901.                     _default_root = Tk()
  1902.                 master = _default_root
  1903.         self.master = master
  1904.         self.tk = master.tk
  1905.         name = None
  1906.         if cnf.has_key('name'):
  1907.             name = cnf['name']
  1908.             del cnf['name']
  1909.         if not name:
  1910.             name = repr(id(self))
  1911.         self._name = name
  1912.         if master._w=='.':
  1913.             self._w = '.' + name
  1914.         else:
  1915.             self._w = master._w + '.' + name
  1916.         self.children = {}
  1917.         if self.master.children.has_key(self._name):
  1918.             self.master.children[self._name].destroy()
  1919.         self.master.children[self._name] = self
  1920.     def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  1921.         """Construct a widget with the parent widget MASTER, a name WIDGETNAME
  1922.         and appropriate options."""
  1923.         if kw:
  1924.             cnf = _cnfmerge((cnf, kw))
  1925.         self.widgetName = widgetName
  1926.         BaseWidget._setup(self, master, cnf)
  1927.         classes = []
  1928.         for k in cnf.keys():
  1929.             if type(k) is ClassType:
  1930.                 classes.append((k, cnf[k]))
  1931.                 del cnf[k]
  1932.         self.tk.call(
  1933.             (widgetName, self._w) + extra + self._options(cnf))
  1934.         for k, v in classes:
  1935.             k.configure(self, v)
  1936.     def destroy(self):
  1937.         """Destroy this and all descendants widgets."""
  1938.         for c in self.children.values(): c.destroy()
  1939.         self.tk.call('destroy', self._w)
  1940.         if self.master.children.has_key(self._name):
  1941.             del self.master.children[self._name]
  1942.         Misc.destroy(self)
  1943.     def _do(self, name, args=()):
  1944.         # XXX Obsolete -- better use self.tk.call directly!
  1945.         return self.tk.call((self._w, name) + args)
  1946.  
  1947. class Widget(BaseWidget, Pack, Place, Grid):
  1948.     """Internal class.
  1949.  
  1950.     Base class for a widget which can be positioned with the geometry managers
  1951.     Pack, Place or Grid."""
  1952.     pass
  1953.  
  1954. class Toplevel(BaseWidget, Wm):
  1955.     """Toplevel widget, e.g. for dialogs."""
  1956.     def __init__(self, master=None, cnf={}, **kw):
  1957.         """Construct a toplevel widget with the parent MASTER.
  1958.  
  1959.         Valid resource names: background, bd, bg, borderwidth, class,
  1960.         colormap, container, cursor, height, highlightbackground,
  1961.         highlightcolor, highlightthickness, menu, relief, screen, takefocus,
  1962.         use, visual, width."""
  1963.         if kw:
  1964.             cnf = _cnfmerge((cnf, kw))
  1965.         extra = ()
  1966.         for wmkey in ['screen', 'class_', 'class', 'visual',
  1967.                   'colormap']:
  1968.             if cnf.has_key(wmkey):
  1969.                 val = cnf[wmkey]
  1970.                 # TBD: a hack needed because some keys
  1971.                 # are not valid as keyword arguments
  1972.                 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  1973.                 else: opt = '-'+wmkey
  1974.                 extra = extra + (opt, val)
  1975.                 del cnf[wmkey]
  1976.         BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  1977.         root = self._root()
  1978.         self.iconname(root.iconname())
  1979.         self.title(root.title())
  1980.         self.protocol("WM_DELETE_WINDOW", self.destroy)
  1981.  
  1982. class Button(Widget):
  1983.     """Button widget."""
  1984.     def __init__(self, master=None, cnf={}, **kw):
  1985.         """Construct a button widget with the parent MASTER.
  1986.  
  1987.         STANDARD OPTIONS
  1988.  
  1989.             activebackground, activeforeground, anchor,
  1990.             background, bitmap, borderwidth, cursor,
  1991.             disabledforeground, font, foreground
  1992.             highlightbackground, highlightcolor,
  1993.             highlightthickness, image, justify,
  1994.             padx, pady, relief, repeatdelay,
  1995.             repeatinterval, takefocus, text,
  1996.             textvariable, underline, wraplength
  1997.  
  1998.         WIDGET-SPECIFIC OPTIONS
  1999.  
  2000.             command, compound, default, height,
  2001.             overrelief, state, width
  2002.         """
  2003.         Widget.__init__(self, master, 'button', cnf, kw)
  2004.  
  2005.     def tkButtonEnter(self, *dummy):
  2006.         self.tk.call('tkButtonEnter', self._w)
  2007.  
  2008.     def tkButtonLeave(self, *dummy):
  2009.         self.tk.call('tkButtonLeave', self._w)
  2010.  
  2011.     def tkButtonDown(self, *dummy):
  2012.         self.tk.call('tkButtonDown', self._w)
  2013.  
  2014.     def tkButtonUp(self, *dummy):
  2015.         self.tk.call('tkButtonUp', self._w)
  2016.  
  2017.     def tkButtonInvoke(self, *dummy):
  2018.         self.tk.call('tkButtonInvoke', self._w)
  2019.  
  2020.     def flash(self):
  2021.         """Flash the button.
  2022.  
  2023.         This is accomplished by redisplaying
  2024.         the button several times, alternating between active and
  2025.         normal colors. At the end of the flash the button is left
  2026.         in the same normal/active state as when the command was
  2027.         invoked. This command is ignored if the button's state is
  2028.         disabled.
  2029.         """
  2030.         self.tk.call(self._w, 'flash')
  2031.  
  2032.     def invoke(self):
  2033.         """Invoke the command associated with the button.
  2034.  
  2035.         The return value is the return value from the command,
  2036.         or an empty string if there is no command associated with
  2037.         the button. This command is ignored if the button's state
  2038.         is disabled.
  2039.         """
  2040.         return self.tk.call(self._w, 'invoke')
  2041.  
  2042. # Indices:
  2043. # XXX I don't like these -- take them away
  2044. def AtEnd():
  2045.     return 'end'
  2046. def AtInsert(*args):
  2047.     s = 'insert'
  2048.     for a in args:
  2049.         if a: s = s + (' ' + a)
  2050.     return s
  2051. def AtSelFirst():
  2052.     return 'sel.first'
  2053. def AtSelLast():
  2054.     return 'sel.last'
  2055. def At(x, y=None):
  2056.     if y is None:
  2057.         return '@%r' % (x,)
  2058.     else:
  2059.         return '@%r,%r' % (x, y)
  2060.  
  2061. class Canvas(Widget):
  2062.     """Canvas widget to display graphical elements like lines or text."""
  2063.     def __init__(self, master=None, cnf={}, **kw):
  2064.         """Construct a canvas widget with the parent MASTER.
  2065.  
  2066.         Valid resource names: background, bd, bg, borderwidth, closeenough,
  2067.         confine, cursor, height, highlightbackground, highlightcolor,
  2068.         highlightthickness, insertbackground, insertborderwidth,
  2069.         insertofftime, insertontime, insertwidth, offset, relief,
  2070.         scrollregion, selectbackground, selectborderwidth, selectforeground,
  2071.         state, takefocus, width, xscrollcommand, xscrollincrement,
  2072.         yscrollcommand, yscrollincrement."""
  2073.         Widget.__init__(self, master, 'canvas', cnf, kw)
  2074.     def addtag(self, *args):
  2075.         """Internal function."""
  2076.         self.tk.call((self._w, 'addtag') + args)
  2077.     def addtag_above(self, newtag, tagOrId):
  2078.         """Add tag NEWTAG to all items above TAGORID."""
  2079.         self.addtag(newtag, 'above', tagOrId)
  2080.     def addtag_all(self, newtag):
  2081.         """Add tag NEWTAG to all items."""
  2082.         self.addtag(newtag, 'all')
  2083.     def addtag_below(self, newtag, tagOrId):
  2084.         """Add tag NEWTAG to all items below TAGORID."""
  2085.         self.addtag(newtag, 'below', tagOrId)
  2086.     def addtag_closest(self, newtag, x, y, halo=None, start=None):
  2087.         """Add tag NEWTAG to item which is closest to pixel at X, Y.
  2088.         If several match take the top-most.
  2089.         All items closer than HALO are considered overlapping (all are
  2090.         closests). If START is specified the next below this tag is taken."""
  2091.         self.addtag(newtag, 'closest', x, y, halo, start)
  2092.     def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  2093.         """Add tag NEWTAG to all items in the rectangle defined
  2094.         by X1,Y1,X2,Y2."""
  2095.         self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  2096.     def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  2097.         """Add tag NEWTAG to all items which overlap the rectangle
  2098.         defined by X1,Y1,X2,Y2."""
  2099.         self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  2100.     def addtag_withtag(self, newtag, tagOrId):
  2101.         """Add tag NEWTAG to all items with TAGORID."""
  2102.         self.addtag(newtag, 'withtag', tagOrId)
  2103.     def bbox(self, *args):
  2104.         """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2105.         which encloses all items with tags specified as arguments."""
  2106.         return self._getints(
  2107.             self.tk.call((self._w, 'bbox') + args)) or None
  2108.     def tag_unbind(self, tagOrId, sequence, funcid=None):
  2109.         """Unbind for all items with TAGORID for event SEQUENCE  the
  2110.         function identified with FUNCID."""
  2111.         self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  2112.         if funcid:
  2113.             self.deletecommand(funcid)
  2114.     def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  2115.         """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
  2116.  
  2117.         An additional boolean parameter ADD specifies whether FUNC will be
  2118.         called additionally to the other bound function or whether it will
  2119.         replace the previous function. See bind for the return value."""
  2120.         return self._bind((self._w, 'bind', tagOrId),
  2121.                   sequence, func, add)
  2122.     def canvasx(self, screenx, gridspacing=None):
  2123.         """Return the canvas x coordinate of pixel position SCREENX rounded
  2124.         to nearest multiple of GRIDSPACING units."""
  2125.         return getdouble(self.tk.call(
  2126.             self._w, 'canvasx', screenx, gridspacing))
  2127.     def canvasy(self, screeny, gridspacing=None):
  2128.         """Return the canvas y coordinate of pixel position SCREENY rounded
  2129.         to nearest multiple of GRIDSPACING units."""
  2130.         return getdouble(self.tk.call(
  2131.             self._w, 'canvasy', screeny, gridspacing))
  2132.     def coords(self, *args):
  2133.         """Return a list of coordinates for the item given in ARGS."""
  2134.         # XXX Should use _flatten on args
  2135.         return map(getdouble,
  2136.                            self.tk.splitlist(
  2137.                    self.tk.call((self._w, 'coords') + args)))
  2138.     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  2139.         """Internal function."""
  2140.         args = _flatten(args)
  2141.         cnf = args[-1]
  2142.         if type(cnf) in (DictionaryType, TupleType):
  2143.             args = args[:-1]
  2144.         else:
  2145.             cnf = {}
  2146.         return getint(self.tk.call(
  2147.             self._w, 'create', itemType,
  2148.             *(args + self._options(cnf, kw))))
  2149.     def create_arc(self, *args, **kw):
  2150.         """Create arc shaped region with coordinates x1,y1,x2,y2."""
  2151.         return self._create('arc', args, kw)
  2152.     def create_bitmap(self, *args, **kw):
  2153.         """Create bitmap with coordinates x1,y1."""
  2154.         return self._create('bitmap', args, kw)
  2155.     def create_image(self, *args, **kw):
  2156.         """Create image item with coordinates x1,y1."""
  2157.         return self._create('image', args, kw)
  2158.     def create_line(self, *args, **kw):
  2159.         """Create line with coordinates x1,y1,...,xn,yn."""
  2160.         return self._create('line', args, kw)
  2161.     def create_oval(self, *args, **kw):
  2162.         """Create oval with coordinates x1,y1,x2,y2."""
  2163.         return self._create('oval', args, kw)
  2164.     def create_polygon(self, *args, **kw):
  2165.         """Create polygon with coordinates x1,y1,...,xn,yn."""
  2166.         return self._create('polygon', args, kw)
  2167.     def create_rectangle(self, *args, **kw):
  2168.         """Create rectangle with coordinates x1,y1,x2,y2."""
  2169.         return self._create('rectangle', args, kw)
  2170.     def create_text(self, *args, **kw):
  2171.         """Create text with coordinates x1,y1."""
  2172.         return self._create('text', args, kw)
  2173.     def create_window(self, *args, **kw):
  2174.         """Create window with coordinates x1,y1,x2,y2."""
  2175.         return self._create('window', args, kw)
  2176.     def dchars(self, *args):
  2177.         """Delete characters of text items identified by tag or id in ARGS (possibly
  2178.         several times) from FIRST to LAST character (including)."""
  2179.         self.tk.call((self._w, 'dchars') + args)
  2180.     def delete(self, *args):
  2181.         """Delete items identified by all tag or ids contained in ARGS."""
  2182.         self.tk.call((self._w, 'delete') + args)
  2183.     def dtag(self, *args):
  2184.         """Delete tag or id given as last arguments in ARGS from items
  2185.         identified by first argument in ARGS."""
  2186.         self.tk.call((self._w, 'dtag') + args)
  2187.     def find(self, *args):
  2188.         """Internal function."""
  2189.         return self._getints(
  2190.             self.tk.call((self._w, 'find') + args)) or ()
  2191.     def find_above(self, tagOrId):
  2192.         """Return items above TAGORID."""
  2193.         return self.find('above', tagOrId)
  2194.     def find_all(self):
  2195.         """Return all items."""
  2196.         return self.find('all')
  2197.     def find_below(self, tagOrId):
  2198.         """Return all items below TAGORID."""
  2199.         return self.find('below', tagOrId)
  2200.     def find_closest(self, x, y, halo=None, start=None):
  2201.         """Return item which is closest to pixel at X, Y.
  2202.         If several match take the top-most.
  2203.         All items closer than HALO are considered overlapping (all are
  2204.         closests). If START is specified the next below this tag is taken."""
  2205.         return self.find('closest', x, y, halo, start)
  2206.     def find_enclosed(self, x1, y1, x2, y2):
  2207.         """Return all items in rectangle defined
  2208.         by X1,Y1,X2,Y2."""
  2209.         return self.find('enclosed', x1, y1, x2, y2)
  2210.     def find_overlapping(self, x1, y1, x2, y2):
  2211.         """Return all items which overlap the rectangle
  2212.         defined by X1,Y1,X2,Y2."""
  2213.         return self.find('overlapping', x1, y1, x2, y2)
  2214.     def find_withtag(self, tagOrId):
  2215.         """Return all items with TAGORID."""
  2216.         return self.find('withtag', tagOrId)
  2217.     def focus(self, *args):
  2218.         """Set focus to the first item specified in ARGS."""
  2219.         return self.tk.call((self._w, 'focus') + args)
  2220.     def gettags(self, *args):
  2221.         """Return tags associated with the first item specified in ARGS."""
  2222.         return self.tk.splitlist(
  2223.             self.tk.call((self._w, 'gettags') + args))
  2224.     def icursor(self, *args):
  2225.         """Set cursor at position POS in the item identified by TAGORID.
  2226.         In ARGS TAGORID must be first."""
  2227.         self.tk.call((self._w, 'icursor') + args)
  2228.     def index(self, *args):
  2229.         """Return position of cursor as integer in item specified in ARGS."""
  2230.         return getint(self.tk.call((self._w, 'index') + args))
  2231.     def insert(self, *args):
  2232.         """Insert TEXT in item TAGORID at position POS. ARGS must
  2233.         be TAGORID POS TEXT."""
  2234.         self.tk.call((self._w, 'insert') + args)
  2235.     def itemcget(self, tagOrId, option):
  2236.         """Return the resource value for an OPTION for item TAGORID."""
  2237.         return self.tk.call(
  2238.             (self._w, 'itemcget') + (tagOrId, '-'+option))
  2239.     def itemconfigure(self, tagOrId, cnf=None, **kw):
  2240.         """Configure resources of an item TAGORID.
  2241.  
  2242.         The values for resources are specified as keyword
  2243.         arguments. To get an overview about
  2244.         the allowed keyword arguments call the method without arguments.
  2245.         """
  2246.         return self._configure(('itemconfigure', tagOrId), cnf, kw)
  2247.     itemconfig = itemconfigure
  2248.     # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
  2249.     # so the preferred name for them is tag_lower, tag_raise
  2250.     # (similar to tag_bind, and similar to the Text widget);
  2251.     # unfortunately can't delete the old ones yet (maybe in 1.6)
  2252.     def tag_lower(self, *args):
  2253.         """Lower an item TAGORID given in ARGS
  2254.         (optional below another item)."""
  2255.         self.tk.call((self._w, 'lower') + args)
  2256.     lower = tag_lower
  2257.     def move(self, *args):
  2258.         """Move an item TAGORID given in ARGS."""
  2259.         self.tk.call((self._w, 'move') + args)
  2260.     def postscript(self, cnf={}, **kw):
  2261.         """Print the contents of the canvas to a postscript
  2262.         file. Valid options: colormap, colormode, file, fontmap,
  2263.         height, pageanchor, pageheight, pagewidth, pagex, pagey,
  2264.         rotate, witdh, x, y."""
  2265.         return self.tk.call((self._w, 'postscript') +
  2266.                     self._options(cnf, kw))
  2267.     def tag_raise(self, *args):
  2268.         """Raise an item TAGORID given in ARGS
  2269.         (optional above another item)."""
  2270.         self.tk.call((self._w, 'raise') + args)
  2271.     lift = tkraise = tag_raise
  2272.     def scale(self, *args):
  2273.         """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
  2274.         self.tk.call((self._w, 'scale') + args)
  2275.     def scan_mark(self, x, y):
  2276.         """Remember the current X, Y coordinates."""
  2277.         self.tk.call(self._w, 'scan', 'mark', x, y)
  2278.     def scan_dragto(self, x, y, gain=10):
  2279.         """Adjust the view of the canvas to GAIN times the
  2280.         difference between X and Y and the coordinates given in
  2281.         scan_mark."""
  2282.         self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
  2283.     def select_adjust(self, tagOrId, index):
  2284.         """Adjust the end of the selection near the cursor of an item TAGORID to index."""
  2285.         self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  2286.     def select_clear(self):
  2287.         """Clear the selection if it is in this widget."""
  2288.         self.tk.call(self._w, 'select', 'clear')
  2289.     def select_from(self, tagOrId, index):
  2290.         """Set the fixed end of a selection in item TAGORID to INDEX."""
  2291.         self.tk.call(self._w, 'select', 'from', tagOrId, index)
  2292.     def select_item(self):
  2293.         """Return the item which has the selection."""
  2294.         return self.tk.call(self._w, 'select', 'item') or None
  2295.     def select_to(self, tagOrId, index):
  2296.         """Set the variable end of a selection in item TAGORID to INDEX."""
  2297.         self.tk.call(self._w, 'select', 'to', tagOrId, index)
  2298.     def type(self, tagOrId):
  2299.         """Return the type of the item TAGORID."""
  2300.         return self.tk.call(self._w, 'type', tagOrId) or None
  2301.     def xview(self, *args):
  2302.         """Query and change horizontal position of the view."""
  2303.         if not args:
  2304.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  2305.         self.tk.call((self._w, 'xview') + args)
  2306.     def xview_moveto(self, fraction):
  2307.         """Adjusts the view in the window so that FRACTION of the
  2308.         total width of the canvas is off-screen to the left."""
  2309.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2310.     def xview_scroll(self, number, what):
  2311.         """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2312.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2313.     def yview(self, *args):
  2314.         """Query and change vertical position of the view."""
  2315.         if not args:
  2316.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  2317.         self.tk.call((self._w, 'yview') + args)
  2318.     def yview_moveto(self, fraction):
  2319.         """Adjusts the view in the window so that FRACTION of the
  2320.         total height of the canvas is off-screen to the top."""
  2321.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  2322.     def yview_scroll(self, number, what):
  2323.         """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2324.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  2325.  
  2326. class Checkbutton(Widget):
  2327.     """Checkbutton widget which is either in on- or off-state."""
  2328.     def __init__(self, master=None, cnf={}, **kw):
  2329.         """Construct a checkbutton widget with the parent MASTER.
  2330.  
  2331.         Valid resource names: activebackground, activeforeground, anchor,
  2332.         background, bd, bg, bitmap, borderwidth, command, cursor,
  2333.         disabledforeground, fg, font, foreground, height,
  2334.         highlightbackground, highlightcolor, highlightthickness, image,
  2335.         indicatoron, justify, offvalue, onvalue, padx, pady, relief,
  2336.         selectcolor, selectimage, state, takefocus, text, textvariable,
  2337.         underline, variable, width, wraplength."""
  2338.         Widget.__init__(self, master, 'checkbutton', cnf, kw)
  2339.     def deselect(self):
  2340.         """Put the button in off-state."""
  2341.         self.tk.call(self._w, 'deselect')
  2342.     def flash(self):
  2343.         """Flash the button."""
  2344.         self.tk.call(self._w, 'flash')
  2345.     def invoke(self):
  2346.         """Toggle the button and invoke a command if given as resource."""
  2347.         return self.tk.call(self._w, 'invoke')
  2348.     def select(self):
  2349.         """Put the button in on-state."""
  2350.         self.tk.call(self._w, 'select')
  2351.     def toggle(self):
  2352.         """Toggle the button."""
  2353.         self.tk.call(self._w, 'toggle')
  2354.  
  2355. class Entry(Widget):
  2356.     """Entry widget which allows to display simple text."""
  2357.     def __init__(self, master=None, cnf={}, **kw):
  2358.         """Construct an entry widget with the parent MASTER.
  2359.  
  2360.         Valid resource names: background, bd, bg, borderwidth, cursor,
  2361.         exportselection, fg, font, foreground, highlightbackground,
  2362.         highlightcolor, highlightthickness, insertbackground,
  2363.         insertborderwidth, insertofftime, insertontime, insertwidth,
  2364.         invalidcommand, invcmd, justify, relief, selectbackground,
  2365.         selectborderwidth, selectforeground, show, state, takefocus,
  2366.         textvariable, validate, validatecommand, vcmd, width,
  2367.         xscrollcommand."""
  2368.         Widget.__init__(self, master, 'entry', cnf, kw)
  2369.     def delete(self, first, last=None):
  2370.         """Delete text from FIRST to LAST (not included)."""
  2371.         self.tk.call(self._w, 'delete', first, last)
  2372.     def get(self):
  2373.         """Return the text."""
  2374.         return self.tk.call(self._w, 'get')
  2375.     def icursor(self, index):
  2376.         """Insert cursor at INDEX."""
  2377.         self.tk.call(self._w, 'icursor', index)
  2378.     def index(self, index):
  2379.         """Return position of cursor."""
  2380.         return getint(self.tk.call(
  2381.             self._w, 'index', index))
  2382.     def insert(self, index, string):
  2383.         """Insert STRING at INDEX."""
  2384.         self.tk.call(self._w, 'insert', index, string)
  2385.     def scan_mark(self, x):
  2386.         """Remember the current X, Y coordinates."""
  2387.         self.tk.call(self._w, 'scan', 'mark', x)
  2388.     def scan_dragto(self, x):
  2389.         """Adjust the view of the canvas to 10 times the
  2390.         difference between X and Y and the coordinates given in
  2391.         scan_mark."""
  2392.         self.tk.call(self._w, 'scan', 'dragto', x)
  2393.     def selection_adjust(self, index):
  2394.         """Adjust the end of the selection near the cursor to INDEX."""
  2395.         self.tk.call(self._w, 'selection', 'adjust', index)
  2396.     select_adjust = selection_adjust
  2397.     def selection_clear(self):
  2398.         """Clear the selection if it is in this widget."""
  2399.         self.tk.call(self._w, 'selection', 'clear')
  2400.     select_clear = selection_clear
  2401.     def selection_from(self, index):
  2402.         """Set the fixed end of a selection to INDEX."""
  2403.         self.tk.call(self._w, 'selection', 'from', index)
  2404.     select_from = selection_from
  2405.     def selection_present(self):
  2406.         """Return whether the widget has the selection."""
  2407.         return self.tk.getboolean(
  2408.             self.tk.call(self._w, 'selection', 'present'))
  2409.     select_present = selection_present
  2410.     def selection_range(self, start, end):
  2411.         """Set the selection from START to END (not included)."""
  2412.         self.tk.call(self._w, 'selection', 'range', start, end)
  2413.     select_range = selection_range
  2414.     def selection_to(self, index):
  2415.         """Set the variable end of a selection to INDEX."""
  2416.         self.tk.call(self._w, 'selection', 'to', index)
  2417.     select_to = selection_to
  2418.     def xview(self, index):
  2419.         """Query and change horizontal position of the view."""
  2420.         self.tk.call(self._w, 'xview', index)
  2421.     def xview_moveto(self, fraction):
  2422.         """Adjust the view in the window so that FRACTION of the
  2423.         total width of the entry is off-screen to the left."""
  2424.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2425.     def xview_scroll(self, number, what):
  2426.         """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2427.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2428.  
  2429. class Frame(Widget):
  2430.     """Frame widget which may contain other widgets and can have a 3D border."""
  2431.     def __init__(self, master=None, cnf={}, **kw):
  2432.         """Construct a frame widget with the parent MASTER.
  2433.  
  2434.         Valid resource names: background, bd, bg, borderwidth, class,
  2435.         colormap, container, cursor, height, highlightbackground,
  2436.         highlightcolor, highlightthickness, relief, takefocus, visual, width."""
  2437.         cnf = _cnfmerge((cnf, kw))
  2438.         extra = ()
  2439.         if cnf.has_key('class_'):
  2440.             extra = ('-class', cnf['class_'])
  2441.             del cnf['class_']
  2442.         elif cnf.has_key('class'):
  2443.             extra = ('-class', cnf['class'])
  2444.             del cnf['class']
  2445.         Widget.__init__(self, master, 'frame', cnf, {}, extra)
  2446.  
  2447. class Label(Widget):
  2448.     """Label widget which can display text and bitmaps."""
  2449.     def __init__(self, master=None, cnf={}, **kw):
  2450.         """Construct a label widget with the parent MASTER.
  2451.  
  2452.         STANDARD OPTIONS
  2453.  
  2454.             activebackground, activeforeground, anchor,
  2455.             background, bitmap, borderwidth, cursor,
  2456.             disabledforeground, font, foreground,
  2457.             highlightbackground, highlightcolor,
  2458.             highlightthickness, image, justify,
  2459.             padx, pady, relief, takefocus, text,
  2460.             textvariable, underline, wraplength
  2461.  
  2462.         WIDGET-SPECIFIC OPTIONS
  2463.  
  2464.             height, state, width
  2465.  
  2466.         """
  2467.         Widget.__init__(self, master, 'label', cnf, kw)
  2468.  
  2469. class Listbox(Widget):
  2470.     """Listbox widget which can display a list of strings."""
  2471.     def __init__(self, master=None, cnf={}, **kw):
  2472.         """Construct a listbox widget with the parent MASTER.
  2473.  
  2474.         Valid resource names: background, bd, bg, borderwidth, cursor,
  2475.         exportselection, fg, font, foreground, height, highlightbackground,
  2476.         highlightcolor, highlightthickness, relief, selectbackground,
  2477.         selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
  2478.         width, xscrollcommand, yscrollcommand, listvariable."""
  2479.         Widget.__init__(self, master, 'listbox', cnf, kw)
  2480.     def activate(self, index):
  2481.         """Activate item identified by INDEX."""
  2482.         self.tk.call(self._w, 'activate', index)
  2483.     def bbox(self, *args):
  2484.         """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2485.         which encloses the item identified by index in ARGS."""
  2486.         return self._getints(
  2487.             self.tk.call((self._w, 'bbox') + args)) or None
  2488.     def curselection(self):
  2489.         """Return list of indices of currently selected item."""
  2490.         # XXX Ought to apply self._getints()...
  2491.         return self.tk.splitlist(self.tk.call(
  2492.             self._w, 'curselection'))
  2493.     def delete(self, first, last=None):
  2494.         """Delete items from FIRST to LAST (not included)."""
  2495.         self.tk.call(self._w, 'delete', first, last)
  2496.     def get(self, first, last=None):
  2497.         """Get list of items from FIRST to LAST (not included)."""
  2498.         if last:
  2499.             return self.tk.splitlist(self.tk.call(
  2500.                 self._w, 'get', first, last))
  2501.         else:
  2502.             return self.tk.call(self._w, 'get', first)
  2503.     def index(self, index):
  2504.         """Return index of item identified with INDEX."""
  2505.         i = self.tk.call(self._w, 'index', index)
  2506.         if i == 'none': return None
  2507.         return getint(i)
  2508.     def insert(self, index, *elements):
  2509.         """Insert ELEMENTS at INDEX."""
  2510.         self.tk.call((self._w, 'insert', index) + elements)
  2511.     def nearest(self, y):
  2512.         """Get index of item which is nearest to y coordinate Y."""
  2513.         return getint(self.tk.call(
  2514.             self._w, 'nearest', y))
  2515.     def scan_mark(self, x, y):
  2516.         """Remember the current X, Y coordinates."""
  2517.         self.tk.call(self._w, 'scan', 'mark', x, y)
  2518.     def scan_dragto(self, x, y):
  2519.         """Adjust the view of the listbox to 10 times the
  2520.         difference between X and Y and the coordinates given in
  2521.         scan_mark."""
  2522.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  2523.     def see(self, index):
  2524.         """Scroll such that INDEX is visible."""
  2525.         self.tk.call(self._w, 'see', index)
  2526.     def selection_anchor(self, index):
  2527.         """Set the fixed end oft the selection to INDEX."""
  2528.         self.tk.call(self._w, 'selection', 'anchor', index)
  2529.     select_anchor = selection_anchor
  2530.     def selection_clear(self, first, last=None):
  2531.         """Clear the selection from FIRST to LAST (not included)."""
  2532.         self.tk.call(self._w,
  2533.                  'selection', 'clear', first, last)
  2534.     select_clear = selection_clear
  2535.     def selection_includes(self, index):
  2536.         """Return 1 if INDEX is part of the selection."""
  2537.         return self.tk.getboolean(self.tk.call(
  2538.             self._w, 'selection', 'includes', index))
  2539.     select_includes = selection_includes
  2540.     def selection_set(self, first, last=None):
  2541.         """Set the selection from FIRST to LAST (not included) without
  2542.         changing the currently selected elements."""
  2543.         self.tk.call(self._w, 'selection', 'set', first, last)
  2544.     select_set = selection_set
  2545.     def size(self):
  2546.         """Return the number of elements in the listbox."""
  2547.         return getint(self.tk.call(self._w, 'size'))
  2548.     def xview(self, *what):
  2549.         """Query and change horizontal position of the view."""
  2550.         if not what:
  2551.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  2552.         self.tk.call((self._w, 'xview') + what)
  2553.     def xview_moveto(self, fraction):
  2554.         """Adjust the view in the window so that FRACTION of the
  2555.         total width of the entry is off-screen to the left."""
  2556.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2557.     def xview_scroll(self, number, what):
  2558.         """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2559.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2560.     def yview(self, *what):
  2561.         """Query and change vertical position of the view."""
  2562.         if not what:
  2563.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  2564.         self.tk.call((self._w, 'yview') + what)
  2565.     def yview_moveto(self, fraction):
  2566.         """Adjust the view in the window so that FRACTION of the
  2567.         total width of the entry is off-screen to the top."""
  2568.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  2569.     def yview_scroll(self, number, what):
  2570.         """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2571.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  2572.     def itemcget(self, index, option):
  2573.         """Return the resource value for an ITEM and an OPTION."""
  2574.         return self.tk.call(
  2575.             (self._w, 'itemcget') + (index, '-'+option))
  2576.     def itemconfigure(self, index, cnf=None, **kw):
  2577.         """Configure resources of an ITEM.
  2578.  
  2579.         The values for resources are specified as keyword arguments.
  2580.         To get an overview about the allowed keyword arguments
  2581.         call the method without arguments.
  2582.         Valid resource names: background, bg, foreground, fg,
  2583.         selectbackground, selectforeground."""
  2584.         return self._configure(('itemconfigure', index), cnf, kw)
  2585.     itemconfig = itemconfigure
  2586.  
  2587. class Menu(Widget):
  2588.     """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
  2589.     def __init__(self, master=None, cnf={}, **kw):
  2590.         """Construct menu widget with the parent MASTER.
  2591.  
  2592.         Valid resource names: activebackground, activeborderwidth,
  2593.         activeforeground, background, bd, bg, borderwidth, cursor,
  2594.         disabledforeground, fg, font, foreground, postcommand, relief,
  2595.         selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
  2596.         Widget.__init__(self, master, 'menu', cnf, kw)
  2597.     def tk_bindForTraversal(self):
  2598.         pass # obsolete since Tk 4.0
  2599.     def tk_mbPost(self):
  2600.         self.tk.call('tk_mbPost', self._w)
  2601.     def tk_mbUnpost(self):
  2602.         self.tk.call('tk_mbUnpost')
  2603.     def tk_traverseToMenu(self, char):
  2604.         self.tk.call('tk_traverseToMenu', self._w, char)
  2605.     def tk_traverseWithinMenu(self, char):
  2606.         self.tk.call('tk_traverseWithinMenu', self._w, char)
  2607.     def tk_getMenuButtons(self):
  2608.         return self.tk.call('tk_getMenuButtons', self._w)
  2609.     def tk_nextMenu(self, count):
  2610.         self.tk.call('tk_nextMenu', count)
  2611.     def tk_nextMenuEntry(self, count):
  2612.         self.tk.call('tk_nextMenuEntry', count)
  2613.     def tk_invokeMenu(self):
  2614.         self.tk.call('tk_invokeMenu', self._w)
  2615.     def tk_firstMenu(self):
  2616.         self.tk.call('tk_firstMenu', self._w)
  2617.     def tk_mbButtonDown(self):
  2618.         self.tk.call('tk_mbButtonDown', self._w)
  2619.     def tk_popup(self, x, y, entry=""):
  2620.         """Post the menu at position X,Y with entry ENTRY."""
  2621.         self.tk.call('tk_popup', self._w, x, y, entry)
  2622.     def activate(self, index):
  2623.         """Activate entry at INDEX."""
  2624.         self.tk.call(self._w, 'activate', index)
  2625.     def add(self, itemType, cnf={}, **kw):
  2626.         """Internal function."""
  2627.         self.tk.call((self._w, 'add', itemType) +
  2628.                  self._options(cnf, kw))
  2629.     def add_cascade(self, cnf={}, **kw):
  2630.         """Add hierarchical menu item."""
  2631.         self.add('cascade', cnf or kw)
  2632.     def add_checkbutton(self, cnf={}, **kw):
  2633.         """Add checkbutton menu item."""
  2634.         self.add('checkbutton', cnf or kw)
  2635.     def add_command(self, cnf={}, **kw):
  2636.         """Add command menu item."""
  2637.         self.add('command', cnf or kw)
  2638.     def add_radiobutton(self, cnf={}, **kw):
  2639.         """Addd radio menu item."""
  2640.         self.add('radiobutton', cnf or kw)
  2641.     def add_separator(self, cnf={}, **kw):
  2642.         """Add separator."""
  2643.         self.add('separator', cnf or kw)
  2644.     def insert(self, index, itemType, cnf={}, **kw):
  2645.         """Internal function."""
  2646.         self.tk.call((self._w, 'insert', index, itemType) +
  2647.                  self._options(cnf, kw))
  2648.     def insert_cascade(self, index, cnf={}, **kw):
  2649.         """Add hierarchical menu item at INDEX."""
  2650.         self.insert(index, 'cascade', cnf or kw)
  2651.     def insert_checkbutton(self, index, cnf={}, **kw):
  2652.         """Add checkbutton menu item at INDEX."""
  2653.         self.insert(index, 'checkbutton', cnf or kw)
  2654.     def insert_command(self, index, cnf={}, **kw):
  2655.         """Add command menu item at INDEX."""
  2656.         self.insert(index, 'command', cnf or kw)
  2657.     def insert_radiobutton(self, index, cnf={}, **kw):
  2658.         """Addd radio menu item at INDEX."""
  2659.         self.insert(index, 'radiobutton', cnf or kw)
  2660.     def insert_separator(self, index, cnf={}, **kw):
  2661.         """Add separator at INDEX."""
  2662.         self.insert(index, 'separator', cnf or kw)
  2663.     def delete(self, index1, index2=None):
  2664.         """Delete menu items between INDEX1 and INDEX2 (not included)."""
  2665.         self.tk.call(self._w, 'delete', index1, index2)
  2666.     def entrycget(self, index, option):
  2667.         """Return the resource value of an menu item for OPTION at INDEX."""
  2668.         return self.tk.call(self._w, 'entrycget', index, '-' + option)
  2669.     def entryconfigure(self, index, cnf=None, **kw):
  2670.         """Configure a menu item at INDEX."""
  2671.         return self._configure(('entryconfigure', index), cnf, kw)
  2672.     entryconfig = entryconfigure
  2673.     def index(self, index):
  2674.         """Return the index of a menu item identified by INDEX."""
  2675.         i = self.tk.call(self._w, 'index', index)
  2676.         if i == 'none': return None
  2677.         return getint(i)
  2678.     def invoke(self, index):
  2679.         """Invoke a menu item identified by INDEX and execute
  2680.         the associated command."""
  2681.         return self.tk.call(self._w, 'invoke', index)
  2682.     def post(self, x, y):
  2683.         """Display a menu at position X,Y."""
  2684.         self.tk.call(self._w, 'post', x, y)
  2685.     def type(self, index):
  2686.         """Return the type of the menu item at INDEX."""
  2687.         return self.tk.call(self._w, 'type', index)
  2688.     def unpost(self):
  2689.         """Unmap a menu."""
  2690.         self.tk.call(self._w, 'unpost')
  2691.     def yposition(self, index):
  2692.         """Return the y-position of the topmost pixel of the menu item at INDEX."""
  2693.         return getint(self.tk.call(
  2694.             self._w, 'yposition', index))
  2695.  
  2696. class Menubutton(Widget):
  2697.     """Menubutton widget, obsolete since Tk8.0."""
  2698.     def __init__(self, master=None, cnf={}, **kw):
  2699.         Widget.__init__(self, master, 'menubutton', cnf, kw)
  2700.  
  2701. class Message(Widget):
  2702.     """Message widget to display multiline text. Obsolete since Label does it too."""
  2703.     def __init__(self, master=None, cnf={}, **kw):
  2704.         Widget.__init__(self, master, 'message', cnf, kw)
  2705.  
  2706. class Radiobutton(Widget):
  2707.     """Radiobutton widget which shows only one of several buttons in on-state."""
  2708.     def __init__(self, master=None, cnf={}, **kw):
  2709.         """Construct a radiobutton widget with the parent MASTER.
  2710.  
  2711.         Valid resource names: activebackground, activeforeground, anchor,
  2712.         background, bd, bg, bitmap, borderwidth, command, cursor,
  2713.         disabledforeground, fg, font, foreground, height,
  2714.         highlightbackground, highlightcolor, highlightthickness, image,
  2715.         indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
  2716.         state, takefocus, text, textvariable, underline, value, variable,
  2717.         width, wraplength."""
  2718.         Widget.__init__(self, master, 'radiobutton', cnf, kw)
  2719.     def deselect(self):
  2720.         """Put the button in off-state."""
  2721.  
  2722.         self.tk.call(self._w, 'deselect')
  2723.     def flash(self):
  2724.         """Flash the button."""
  2725.         self.tk.call(self._w, 'flash')
  2726.     def invoke(self):
  2727.         """Toggle the button and invoke a command if given as resource."""
  2728.         return self.tk.call(self._w, 'invoke')
  2729.     def select(self):
  2730.         """Put the button in on-state."""
  2731.         self.tk.call(self._w, 'select')
  2732.  
  2733. class Scale(Widget):
  2734.     """Scale widget which can display a numerical scale."""
  2735.     def __init__(self, master=None, cnf={}, **kw):
  2736.         """Construct a scale widget with the parent MASTER.
  2737.  
  2738.         Valid resource names: activebackground, background, bigincrement, bd,
  2739.         bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
  2740.         highlightbackground, highlightcolor, highlightthickness, label,
  2741.         length, orient, relief, repeatdelay, repeatinterval, resolution,
  2742.         showvalue, sliderlength, sliderrelief, state, takefocus,
  2743.         tickinterval, to, troughcolor, variable, width."""
  2744.         Widget.__init__(self, master, 'scale', cnf, kw)
  2745.     def get(self):
  2746.         """Get the current value as integer or float."""
  2747.         value = self.tk.call(self._w, 'get')
  2748.         try:
  2749.             return getint(value)
  2750.         except ValueError:
  2751.             return getdouble(value)
  2752.     def set(self, value):
  2753.         """Set the value to VALUE."""
  2754.         self.tk.call(self._w, 'set', value)
  2755.     def coords(self, value=None):
  2756.         """Return a tuple (X,Y) of the point along the centerline of the
  2757.         trough that corresponds to VALUE or the current value if None is
  2758.         given."""
  2759.  
  2760.         return self._getints(self.tk.call(self._w, 'coords', value))
  2761.     def identify(self, x, y):
  2762.         """Return where the point X,Y lies. Valid return values are "slider",
  2763.         "though1" and "though2"."""
  2764.         return self.tk.call(self._w, 'identify', x, y)
  2765.  
  2766. class Scrollbar(Widget):
  2767.     """Scrollbar widget which displays a slider at a certain position."""
  2768.     def __init__(self, master=None, cnf={}, **kw):
  2769.         """Construct a scrollbar widget with the parent MASTER.
  2770.  
  2771.         Valid resource names: activebackground, activerelief,
  2772.         background, bd, bg, borderwidth, command, cursor,
  2773.         elementborderwidth, highlightbackground,
  2774.         highlightcolor, highlightthickness, jump, orient,
  2775.         relief, repeatdelay, repeatinterval, takefocus,
  2776.         troughcolor, width."""
  2777.         Widget.__init__(self, master, 'scrollbar', cnf, kw)
  2778.     def activate(self, index):
  2779.         """Display the element at INDEX with activebackground and activerelief.
  2780.         INDEX can be "arrow1","slider" or "arrow2"."""
  2781.         self.tk.call(self._w, 'activate', index)
  2782.     def delta(self, deltax, deltay):
  2783.         """Return the fractional change of the scrollbar setting if it
  2784.         would be moved by DELTAX or DELTAY pixels."""
  2785.         return getdouble(
  2786.             self.tk.call(self._w, 'delta', deltax, deltay))
  2787.     def fraction(self, x, y):
  2788.         """Return the fractional value which corresponds to a slider
  2789.         position of X,Y."""
  2790.         return getdouble(self.tk.call(self._w, 'fraction', x, y))
  2791.     def identify(self, x, y):
  2792.         """Return the element under position X,Y as one of
  2793.         "arrow1","slider","arrow2" or ""."""
  2794.         return self.tk.call(self._w, 'identify', x, y)
  2795.     def get(self):
  2796.         """Return the current fractional values (upper and lower end)
  2797.         of the slider position."""
  2798.         return self._getdoubles(self.tk.call(self._w, 'get'))
  2799.     def set(self, *args):
  2800.         """Set the fractional values of the slider position (upper and
  2801.         lower ends as value between 0 and 1)."""
  2802.         self.tk.call((self._w, 'set') + args)
  2803.  
  2804.  
  2805.  
  2806. class Text(Widget):
  2807.     """Text widget which can display text in various forms."""
  2808.     def __init__(self, master=None, cnf={}, **kw):
  2809.         """Construct a text widget with the parent MASTER.
  2810.  
  2811.         STANDARD OPTIONS
  2812.  
  2813.             background, borderwidth, cursor,
  2814.             exportselection, font, foreground,
  2815.             highlightbackground, highlightcolor,
  2816.             highlightthickness, insertbackground,
  2817.             insertborderwidth, insertofftime,
  2818.             insertontime, insertwidth, padx, pady,
  2819.             relief, selectbackground,
  2820.             selectborderwidth, selectforeground,
  2821.             setgrid, takefocus,
  2822.             xscrollcommand, yscrollcommand,
  2823.  
  2824.         WIDGET-SPECIFIC OPTIONS
  2825.  
  2826.             autoseparators, height, maxundo,
  2827.             spacing1, spacing2, spacing3,
  2828.             state, tabs, undo, width, wrap,
  2829.  
  2830.         """
  2831.         Widget.__init__(self, master, 'text', cnf, kw)
  2832.     def bbox(self, *args):
  2833.         """Return a tuple of (x,y,width,height) which gives the bounding
  2834.         box of the visible part of the character at the index in ARGS."""
  2835.         return self._getints(
  2836.             self.tk.call((self._w, 'bbox') + args)) or None
  2837.     def tk_textSelectTo(self, index):
  2838.         self.tk.call('tk_textSelectTo', self._w, index)
  2839.     def tk_textBackspace(self):
  2840.         self.tk.call('tk_textBackspace', self._w)
  2841.     def tk_textIndexCloser(self, a, b, c):
  2842.         self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  2843.     def tk_textResetAnchor(self, index):
  2844.         self.tk.call('tk_textResetAnchor', self._w, index)
  2845.     def compare(self, index1, op, index2):
  2846.         """Return whether between index INDEX1 and index INDEX2 the
  2847.         relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
  2848.         return self.tk.getboolean(self.tk.call(
  2849.             self._w, 'compare', index1, op, index2))
  2850.     def debug(self, boolean=None):
  2851.         """Turn on the internal consistency checks of the B-Tree inside the text
  2852.         widget according to BOOLEAN."""
  2853.         return self.tk.getboolean(self.tk.call(
  2854.             self._w, 'debug', boolean))
  2855.     def delete(self, index1, index2=None):
  2856.         """Delete the characters between INDEX1 and INDEX2 (not included)."""
  2857.         self.tk.call(self._w, 'delete', index1, index2)
  2858.     def dlineinfo(self, index):
  2859.         """Return tuple (x,y,width,height,baseline) giving the bounding box
  2860.         and baseline position of the visible part of the line containing
  2861.         the character at INDEX."""
  2862.         return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  2863.     def dump(self, index1, index2=None, command=None, **kw):
  2864.         """Return the contents of the widget between index1 and index2.
  2865.  
  2866.         The type of contents returned in filtered based on the keyword
  2867.         parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
  2868.         given and true, then the corresponding items are returned. The result
  2869.         is a list of triples of the form (key, value, index). If none of the
  2870.         keywords are true then 'all' is used by default.
  2871.  
  2872.         If the 'command' argument is given, it is called once for each element
  2873.         of the list of triples, with the values of each triple serving as the
  2874.         arguments to the function. In this case the list is not returned."""
  2875.         args = []
  2876.         func_name = None
  2877.         result = None
  2878.         if not command:
  2879.             # Never call the dump command without the -command flag, since the
  2880.             # output could involve Tcl quoting and would be a pain to parse
  2881.             # right. Instead just set the command to build a list of triples
  2882.             # as if we had done the parsing.
  2883.             result = []
  2884.             def append_triple(key, value, index, result=result):
  2885.                 result.append((key, value, index))
  2886.             command = append_triple
  2887.         try:
  2888.             if not isinstance(command, str):
  2889.                 func_name = command = self._register(command)
  2890.             args += ["-command", command]
  2891.             for key in kw:
  2892.                 if kw[key]: args.append("-" + key)
  2893.             args.append(index1)
  2894.             if index2:
  2895.                 args.append(index2)
  2896.             self.tk.call(self._w, "dump", *args)
  2897.             return result
  2898.         finally:
  2899.             if func_name:
  2900.                 self.deletecommand(func_name)
  2901.  
  2902.     ## new in tk8.4
  2903.     def edit(self, *args):
  2904.         """Internal method
  2905.  
  2906.         This method controls the undo mechanism and
  2907.         the modified flag. The exact behavior of the
  2908.         command depends on the option argument that
  2909.         follows the edit argument. The following forms
  2910.         of the command are currently supported:
  2911.  
  2912.         edit_modified, edit_redo, edit_reset, edit_separator
  2913.         and edit_undo
  2914.  
  2915.         """
  2916.         return self._getints(
  2917.             self.tk.call((self._w, 'edit') + args)) or ()
  2918.  
  2919.     def edit_modified(self, arg=None):
  2920.         """Get or Set the modified flag
  2921.  
  2922.         If arg is not specified, returns the modified
  2923.         flag of the widget. The insert, delete, edit undo and
  2924.         edit redo commands or the user can set or clear the
  2925.         modified flag. If boolean is specified, sets the
  2926.         modified flag of the widget to arg.
  2927.         """
  2928.         return self.edit("modified", arg)
  2929.  
  2930.     def edit_redo(self):
  2931.         """Redo the last undone edit
  2932.  
  2933.         When the undo option is true, reapplies the last
  2934.         undone edits provided no other edits were done since
  2935.         then. Generates an error when the redo stack is empty.
  2936.         Does nothing when the undo option is false.
  2937.         """
  2938.         return self.edit("redo")
  2939.  
  2940.     def edit_reset(self):
  2941.         """Clears the undo and redo stacks
  2942.         """
  2943.         return self.edit("reset")
  2944.  
  2945.     def edit_separator(self):
  2946.         """Inserts a separator (boundary) on the undo stack.
  2947.  
  2948.         Does nothing when the undo option is false
  2949.         """
  2950.         return self.edit("separator")
  2951.  
  2952.     def edit_undo(self):
  2953.         """Undoes the last edit action
  2954.  
  2955.         If the undo option is true. An edit action is defined
  2956.         as all the insert and delete commands that are recorded
  2957.         on the undo stack in between two separators. Generates
  2958.         an error when the undo stack is empty. Does nothing
  2959.         when the undo option is false
  2960.         """
  2961.         return self.edit("undo")
  2962.  
  2963.     def get(self, index1, index2=None):
  2964.         """Return the text from INDEX1 to INDEX2 (not included)."""
  2965.         return self.tk.call(self._w, 'get', index1, index2)
  2966.     # (Image commands are new in 8.0)
  2967.     def image_cget(self, index, option):
  2968.         """Return the value of OPTION of an embedded image at INDEX."""
  2969.         if option[:1] != "-":
  2970.             option = "-" + option
  2971.         if option[-1:] == "_":
  2972.             option = option[:-1]
  2973.         return self.tk.call(self._w, "image", "cget", index, option)
  2974.     def image_configure(self, index, cnf=None, **kw):
  2975.         """Configure an embedded image at INDEX."""
  2976.         return self._configure(('image', 'configure', index), cnf, kw)
  2977.     def image_create(self, index, cnf={}, **kw):
  2978.         """Create an embedded image at INDEX."""
  2979.         return self.tk.call(
  2980.                  self._w, "image", "create", index,
  2981.                  *self._options(cnf, kw))
  2982.     def image_names(self):
  2983.         """Return all names of embedded images in this widget."""
  2984.         return self.tk.call(self._w, "image", "names")
  2985.     def index(self, index):
  2986.         """Return the index in the form line.char for INDEX."""
  2987.         return self.tk.call(self._w, 'index', index)
  2988.     def insert(self, index, chars, *args):
  2989.         """Insert CHARS before the characters at INDEX. An additional
  2990.         tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
  2991.         self.tk.call((self._w, 'insert', index, chars) + args)
  2992.     def mark_gravity(self, markName, direction=None):
  2993.         """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
  2994.         Return the current value if None is given for DIRECTION."""
  2995.         return self.tk.call(
  2996.             (self._w, 'mark', 'gravity', markName, direction))
  2997.     def mark_names(self):
  2998.         """Return all mark names."""
  2999.         return self.tk.splitlist(self.tk.call(
  3000.             self._w, 'mark', 'names'))
  3001.     def mark_set(self, markName, index):
  3002.         """Set mark MARKNAME before the character at INDEX."""
  3003.         self.tk.call(self._w, 'mark', 'set', markName, index)
  3004.     def mark_unset(self, *markNames):
  3005.         """Delete all marks in MARKNAMES."""
  3006.         self.tk.call((self._w, 'mark', 'unset') + markNames)
  3007.     def mark_next(self, index):
  3008.         """Return the name of the next mark after INDEX."""
  3009.         return self.tk.call(self._w, 'mark', 'next', index) or None
  3010.     def mark_previous(self, index):
  3011.         """Return the name of the previous mark before INDEX."""
  3012.         return self.tk.call(self._w, 'mark', 'previous', index) or None
  3013.     def scan_mark(self, x, y):
  3014.         """Remember the current X, Y coordinates."""
  3015.         self.tk.call(self._w, 'scan', 'mark', x, y)
  3016.     def scan_dragto(self, x, y):
  3017.         """Adjust the view of the text to 10 times the
  3018.         difference between X and Y and the coordinates given in
  3019.         scan_mark."""
  3020.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  3021.     def search(self, pattern, index, stopindex=None,
  3022.            forwards=None, backwards=None, exact=None,
  3023.            regexp=None, nocase=None, count=None):
  3024.         """Search PATTERN beginning from INDEX until STOPINDEX.
  3025.         Return the index of the first character of a match or an empty string."""
  3026.         args = [self._w, 'search']
  3027.         if forwards: args.append('-forwards')
  3028.         if backwards: args.append('-backwards')
  3029.         if exact: args.append('-exact')
  3030.         if regexp: args.append('-regexp')
  3031.         if nocase: args.append('-nocase')
  3032.         if count: args.append('-count'); args.append(count)
  3033.         if pattern[0] == '-': args.append('--')
  3034.         args.append(pattern)
  3035.         args.append(index)
  3036.         if stopindex: args.append(stopindex)
  3037.         return self.tk.call(tuple(args))
  3038.     def see(self, index):
  3039.         """Scroll such that the character at INDEX is visible."""
  3040.         self.tk.call(self._w, 'see', index)
  3041.     def tag_add(self, tagName, index1, *args):
  3042.         """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
  3043.         Additional pairs of indices may follow in ARGS."""
  3044.         self.tk.call(
  3045.             (self._w, 'tag', 'add', tagName, index1) + args)
  3046.     def tag_unbind(self, tagName, sequence, funcid=None):
  3047.         """Unbind for all characters with TAGNAME for event SEQUENCE  the
  3048.         function identified with FUNCID."""
  3049.         self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  3050.         if funcid:
  3051.             self.deletecommand(funcid)
  3052.     def tag_bind(self, tagName, sequence, func, add=None):
  3053.         """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
  3054.  
  3055.         An additional boolean parameter ADD specifies whether FUNC will be
  3056.         called additionally to the other bound function or whether it will
  3057.         replace the previous function. See bind for the return value."""
  3058.         return self._bind((self._w, 'tag', 'bind', tagName),
  3059.                   sequence, func, add)
  3060.     def tag_cget(self, tagName, option):
  3061.         """Return the value of OPTION for tag TAGNAME."""
  3062.         if option[:1] != '-':
  3063.             option = '-' + option
  3064.         if option[-1:] == '_':
  3065.             option = option[:-1]
  3066.         return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  3067.     def tag_configure(self, tagName, cnf=None, **kw):
  3068.         """Configure a tag TAGNAME."""
  3069.         return self._configure(('tag', 'configure', tagName), cnf, kw)
  3070.     tag_config = tag_configure
  3071.     def tag_delete(self, *tagNames):
  3072.         """Delete all tags in TAGNAMES."""
  3073.         self.tk.call((self._w, 'tag', 'delete') + tagNames)
  3074.     def tag_lower(self, tagName, belowThis=None):
  3075.         """Change the priority of tag TAGNAME such that it is lower
  3076.         than the priority of BELOWTHIS."""
  3077.         self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  3078.     def tag_names(self, index=None):
  3079.         """Return a list of all tag names."""
  3080.         return self.tk.splitlist(
  3081.             self.tk.call(self._w, 'tag', 'names', index))
  3082.     def tag_nextrange(self, tagName, index1, index2=None):
  3083.         """Return a list of start and end index for the first sequence of
  3084.         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3085.         The text is searched forward from INDEX1."""
  3086.         return self.tk.splitlist(self.tk.call(
  3087.             self._w, 'tag', 'nextrange', tagName, index1, index2))
  3088.     def tag_prevrange(self, tagName, index1, index2=None):
  3089.         """Return a list of start and end index for the first sequence of
  3090.         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3091.         The text is searched backwards from INDEX1."""
  3092.         return self.tk.splitlist(self.tk.call(
  3093.             self._w, 'tag', 'prevrange', tagName, index1, index2))
  3094.     def tag_raise(self, tagName, aboveThis=None):
  3095.         """Change the priority of tag TAGNAME such that it is higher
  3096.         than the priority of ABOVETHIS."""
  3097.         self.tk.call(
  3098.             self._w, 'tag', 'raise', tagName, aboveThis)
  3099.     def tag_ranges(self, tagName):
  3100.         """Return a list of ranges of text which have tag TAGNAME."""
  3101.         return self.tk.splitlist(self.tk.call(
  3102.             self._w, 'tag', 'ranges', tagName))
  3103.     def tag_remove(self, tagName, index1, index2=None):
  3104.         """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
  3105.         self.tk.call(
  3106.             self._w, 'tag', 'remove', tagName, index1, index2)
  3107.     def window_cget(self, index, option):
  3108.         """Return the value of OPTION of an embedded window at INDEX."""
  3109.         if option[:1] != '-':
  3110.             option = '-' + option
  3111.         if option[-1:] == '_':
  3112.             option = option[:-1]
  3113.         return self.tk.call(self._w, 'window', 'cget', index, option)
  3114.     def window_configure(self, index, cnf=None, **kw):
  3115.         """Configure an embedded window at INDEX."""
  3116.         return self._configure(('window', 'configure', index), cnf, kw)
  3117.     window_config = window_configure
  3118.     def window_create(self, index, cnf={}, **kw):
  3119.         """Create a window at INDEX."""
  3120.         self.tk.call(
  3121.               (self._w, 'window', 'create', index)
  3122.               + self._options(cnf, kw))
  3123.     def window_names(self):
  3124.         """Return all names of embedded windows in this widget."""
  3125.         return self.tk.splitlist(
  3126.             self.tk.call(self._w, 'window', 'names'))
  3127.     def xview(self, *what):
  3128.         """Query and change horizontal position of the view."""
  3129.         if not what:
  3130.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  3131.         self.tk.call((self._w, 'xview') + what)
  3132.     def xview_moveto(self, fraction):
  3133.         """Adjusts the view in the window so that FRACTION of the
  3134.         total width of the canvas is off-screen to the left."""
  3135.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  3136.     def xview_scroll(self, number, what):
  3137.         """Shift the x-view according to NUMBER which is measured
  3138.         in "units" or "pages" (WHAT)."""
  3139.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  3140.     def yview(self, *what):
  3141.         """Query and change vertical position of the view."""
  3142.         if not what:
  3143.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  3144.         self.tk.call((self._w, 'yview') + what)
  3145.     def yview_moveto(self, fraction):
  3146.         """Adjusts the view in the window so that FRACTION of the
  3147.         total height of the canvas is off-screen to the top."""
  3148.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  3149.     def yview_scroll(self, number, what):
  3150.         """Shift the y-view according to NUMBER which is measured
  3151.         in "units" or "pages" (WHAT)."""
  3152.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  3153.     def yview_pickplace(self, *what):
  3154.         """Obsolete function, use see."""
  3155.         self.tk.call((self._w, 'yview', '-pickplace') + what)
  3156.  
  3157.  
  3158. class _setit:
  3159.     """Internal class. It wraps the command in the widget OptionMenu."""
  3160.     def __init__(self, var, value, callback=None):
  3161.         self.__value = value
  3162.         self.__var = var
  3163.         self.__callback = callback
  3164.     def __call__(self, *args):
  3165.         self.__var.set(self.__value)
  3166.         if self.__callback:
  3167.             self.__callback(self.__value, *args)
  3168.  
  3169. class OptionMenu(Menubutton):
  3170.     """OptionMenu which allows the user to select a value from a menu."""
  3171.     def __init__(self, master, variable, value, *values, **kwargs):
  3172.         """Construct an optionmenu widget with the parent MASTER, with
  3173.         the resource textvariable set to VARIABLE, the initially selected
  3174.         value VALUE, the other menu values VALUES and an additional
  3175.         keyword argument command."""
  3176.         kw = {"borderwidth": 2, "textvariable": variable,
  3177.               "indicatoron": 1, "relief": RAISED, "anchor": "c",
  3178.               "highlightthickness": 2}
  3179.         Widget.__init__(self, master, "menubutton", kw)
  3180.         self.widgetName = 'tk_optionMenu'
  3181.         menu = self.__menu = Menu(self, name="menu", tearoff=0)
  3182.         self.menuname = menu._w
  3183.         # 'command' is the only supported keyword
  3184.         callback = kwargs.get('command')
  3185.         if kwargs.has_key('command'):
  3186.             del kwargs['command']
  3187.         if kwargs:
  3188.             raise TclError, 'unknown option -'+kwargs.keys()[0]
  3189.         menu.add_command(label=value,
  3190.                  command=_setit(variable, value, callback))
  3191.         for v in values:
  3192.             menu.add_command(label=v,
  3193.                      command=_setit(variable, v, callback))
  3194.         self["menu"] = menu
  3195.  
  3196.     def __getitem__(self, name):
  3197.         if name == 'menu':
  3198.             return self.__menu
  3199.         return Widget.__getitem__(self, name)
  3200.  
  3201.     def destroy(self):
  3202.         """Destroy this widget and the associated menu."""
  3203.         Menubutton.destroy(self)
  3204.         self.__menu = None
  3205.  
  3206. class Image:
  3207.     """Base class for images."""
  3208.     _last_id = 0
  3209.     def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  3210.         self.name = None
  3211.         if not master:
  3212.             master = _default_root
  3213.             if not master:
  3214.                 raise RuntimeError, 'Too early to create image'
  3215.         self.tk = master.tk
  3216.         if not name:
  3217.             Image._last_id += 1
  3218.             name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
  3219.             # The following is needed for systems where id(x)
  3220.             # can return a negative number, such as Linux/m68k:
  3221.             if name[0] == '-': name = '_' + name[1:]
  3222.         if kw and cnf: cnf = _cnfmerge((cnf, kw))
  3223.         elif kw: cnf = kw
  3224.         options = ()
  3225.         for k, v in cnf.items():
  3226.             if callable(v):
  3227.                 v = self._register(v)
  3228.             options = options + ('-'+k, v)
  3229.         self.tk.call(('image', 'create', imgtype, name,) + options)
  3230.         self.name = name
  3231.     def __str__(self): return self.name
  3232.     def __del__(self):
  3233.         if self.name:
  3234.             try:
  3235.                 self.tk.call('image', 'delete', self.name)
  3236.             except TclError:
  3237.                 # May happen if the root was destroyed
  3238.                 pass
  3239.     def __setitem__(self, key, value):
  3240.         self.tk.call(self.name, 'configure', '-'+key, value)
  3241.     def __getitem__(self, key):
  3242.         return self.tk.call(self.name, 'configure', '-'+key)
  3243.     def configure(self, **kw):
  3244.         """Configure the image."""
  3245.         res = ()
  3246.         for k, v in _cnfmerge(kw).items():
  3247.             if v is not None:
  3248.                 if k[-1] == '_': k = k[:-1]
  3249.                 if callable(v):
  3250.                     v = self._register(v)
  3251.                 res = res + ('-'+k, v)
  3252.         self.tk.call((self.name, 'config') + res)
  3253.     config = configure
  3254.     def height(self):
  3255.         """Return the height of the image."""
  3256.         return getint(
  3257.             self.tk.call('image', 'height', self.name))
  3258.     def type(self):
  3259.         """Return the type of the imgage, e.g. "photo" or "bitmap"."""
  3260.         return self.tk.call('image', 'type', self.name)
  3261.     def width(self):
  3262.         """Return the width of the image."""
  3263.         return getint(
  3264.             self.tk.call('image', 'width', self.name))
  3265.  
  3266. class PhotoImage(Image):
  3267.     """Widget which can display colored images in GIF, PPM/PGM format."""
  3268.     def __init__(self, name=None, cnf={}, master=None, **kw):
  3269.         """Create an image with NAME.
  3270.  
  3271.         Valid resource names: data, format, file, gamma, height, palette,
  3272.         width."""
  3273.         Image.__init__(self, 'photo', name, cnf, master, **kw)
  3274.     def blank(self):
  3275.         """Display a transparent image."""
  3276.         self.tk.call(self.name, 'blank')
  3277.     def cget(self, option):
  3278.         """Return the value of OPTION."""
  3279.         return self.tk.call(self.name, 'cget', '-' + option)
  3280.     # XXX config
  3281.     def __getitem__(self, key):
  3282.         return self.tk.call(self.name, 'cget', '-' + key)
  3283.     # XXX copy -from, -to, ...?
  3284.     def copy(self):
  3285.         """Return a new PhotoImage with the same image as this widget."""
  3286.         destImage = PhotoImage()
  3287.         self.tk.call(destImage, 'copy', self.name)
  3288.         return destImage
  3289.     def zoom(self,x,y=''):
  3290.         """Return a new PhotoImage with the same image as this widget
  3291.         but zoom it with X and Y."""
  3292.         destImage = PhotoImage()
  3293.         if y=='': y=x
  3294.         self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  3295.         return destImage
  3296.     def subsample(self,x,y=''):
  3297.         """Return a new PhotoImage based on the same image as this widget
  3298.         but use only every Xth or Yth pixel."""
  3299.         destImage = PhotoImage()
  3300.         if y=='': y=x
  3301.         self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  3302.         return destImage
  3303.     def get(self, x, y):
  3304.         """Return the color (red, green, blue) of the pixel at X,Y."""
  3305.         return self.tk.call(self.name, 'get', x, y)
  3306.     def put(self, data, to=None):
  3307.         """Put row formated colors to image starting from
  3308.         position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
  3309.         args = (self.name, 'put', data)
  3310.         if to:
  3311.             if to[0] == '-to':
  3312.                 to = to[1:]
  3313.             args = args + ('-to',) + tuple(to)
  3314.         self.tk.call(args)
  3315.     # XXX read
  3316.     def write(self, filename, format=None, from_coords=None):
  3317.         """Write image to file FILENAME in FORMAT starting from
  3318.         position FROM_COORDS."""
  3319.         args = (self.name, 'write', filename)
  3320.         if format:
  3321.             args = args + ('-format', format)
  3322.         if from_coords:
  3323.             args = args + ('-from',) + tuple(from_coords)
  3324.         self.tk.call(args)
  3325.  
  3326. class BitmapImage(Image):
  3327.     """Widget which can display a bitmap."""
  3328.     def __init__(self, name=None, cnf={}, master=None, **kw):
  3329.         """Create a bitmap with NAME.
  3330.  
  3331.         Valid resource names: background, data, file, foreground, maskdata, maskfile."""
  3332.         Image.__init__(self, 'bitmap', name, cnf, master, **kw)
  3333.  
  3334. def image_names(): return _default_root.tk.call('image', 'names')
  3335. def image_types(): return _default_root.tk.call('image', 'types')
  3336.  
  3337.  
  3338. class Spinbox(Widget):
  3339.     """spinbox widget."""
  3340.     def __init__(self, master=None, cnf={}, **kw):
  3341.         """Construct a spinbox widget with the parent MASTER.
  3342.  
  3343.         STANDARD OPTIONS
  3344.  
  3345.             activebackground, background, borderwidth,
  3346.             cursor, exportselection, font, foreground,
  3347.             highlightbackground, highlightcolor,
  3348.             highlightthickness, insertbackground,
  3349.             insertborderwidth, insertofftime,
  3350.             insertontime, insertwidth, justify, relief,
  3351.             repeatdelay, repeatinterval,
  3352.             selectbackground, selectborderwidth
  3353.             selectforeground, takefocus, textvariable
  3354.             xscrollcommand.
  3355.  
  3356.         WIDGET-SPECIFIC OPTIONS
  3357.  
  3358.             buttonbackground, buttoncursor,
  3359.             buttondownrelief, buttonuprelief,
  3360.             command, disabledbackground,
  3361.             disabledforeground, format, from,
  3362.             invalidcommand, increment,
  3363.             readonlybackground, state, to,
  3364.             validate, validatecommand values,
  3365.             width, wrap,
  3366.         """
  3367.         Widget.__init__(self, master, 'spinbox', cnf, kw)
  3368.  
  3369.     def bbox(self, index):
  3370.         """Return a tuple of X1,Y1,X2,Y2 coordinates for a
  3371.         rectangle which encloses the character given by index.
  3372.  
  3373.         The first two elements of the list give the x and y
  3374.         coordinates of the upper-left corner of the screen
  3375.         area covered by the character (in pixels relative
  3376.         to the widget) and the last two elements give the
  3377.         width and height of the character, in pixels. The
  3378.         bounding box may refer to a region outside the
  3379.         visible area of the window.
  3380.         """
  3381.         return self.tk.call(self._w, 'bbox', index)
  3382.  
  3383.     def delete(self, first, last=None):
  3384.         """Delete one or more elements of the spinbox.
  3385.  
  3386.         First is the index of the first character to delete,
  3387.         and last is the index of the character just after
  3388.         the last one to delete. If last isn't specified it
  3389.         defaults to first+1, i.e. a single character is
  3390.         deleted.  This command returns an empty string.
  3391.         """
  3392.         return self.tk.call(self._w, 'delete', first, last)
  3393.  
  3394.     def get(self):
  3395.         """Returns the spinbox's string"""
  3396.         return self.tk.call(self._w, 'get')
  3397.  
  3398.     def icursor(self, index):
  3399.         """Alter the position of the insertion cursor.
  3400.  
  3401.         The insertion cursor will be displayed just before
  3402.         the character given by index. Returns an empty string
  3403.         """
  3404.         return self.tk.call(self._w, 'icursor', index)
  3405.  
  3406.     def identify(self, x, y):
  3407.         """Returns the name of the widget at position x, y
  3408.  
  3409.         Return value is one of: none, buttondown, buttonup, entry
  3410.         """
  3411.         return self.tk.call(self._w, 'identify', x, y)
  3412.  
  3413.     def index(self, index):
  3414.         """Returns the numerical index corresponding to index
  3415.         """
  3416.         return self.tk.call(self._w, 'index', index)
  3417.  
  3418.     def insert(self, index, s):
  3419.         """Insert string s at index
  3420.  
  3421.          Returns an empty string.
  3422.         """
  3423.         return self.tk.call(self._w, 'insert', index, s)
  3424.  
  3425.     def invoke(self, element):
  3426.         """Causes the specified element to be invoked
  3427.  
  3428.         The element could be buttondown or buttonup
  3429.         triggering the action associated with it.
  3430.         """
  3431.         return self.tk.call(self._w, 'invoke', element)
  3432.  
  3433.     def scan(self, *args):
  3434.         """Internal function."""
  3435.         return self._getints(
  3436.             self.tk.call((self._w, 'scan') + args)) or ()
  3437.  
  3438.     def scan_mark(self, x):
  3439.         """Records x and the current view in the spinbox window;
  3440.  
  3441.         used in conjunction with later scan dragto commands.
  3442.         Typically this command is associated with a mouse button
  3443.         press in the widget. It returns an empty string.
  3444.         """
  3445.         return self.scan("mark", x)
  3446.  
  3447.     def scan_dragto(self, x):
  3448.         """Compute the difference between the given x argument
  3449.         and the x argument to the last scan mark command
  3450.  
  3451.         It then adjusts the view left or right by 10 times the
  3452.         difference in x-coordinates. This command is typically
  3453.         associated with mouse motion events in the widget, to
  3454.         produce the effect of dragging the spinbox at high speed
  3455.         through the window. The return value is an empty string.
  3456.         """
  3457.         return self.scan("dragto", x)
  3458.  
  3459.     def selection(self, *args):
  3460.         """Internal function."""
  3461.         return self._getints(
  3462.             self.tk.call((self._w, 'selection') + args)) or ()
  3463.  
  3464.     def selection_adjust(self, index):
  3465.         """Locate the end of the selection nearest to the character
  3466.         given by index,
  3467.  
  3468.         Then adjust that end of the selection to be at index
  3469.         (i.e including but not going beyond index). The other
  3470.         end of the selection is made the anchor point for future
  3471.         select to commands. If the selection isn't currently in
  3472.         the spinbox, then a new selection is created to include
  3473.         the characters between index and the most recent selection
  3474.         anchor point, inclusive. Returns an empty string.
  3475.         """
  3476.         return self.selection("adjust", index)
  3477.  
  3478.     def selection_clear(self):
  3479.         """Clear the selection
  3480.  
  3481.         If the selection isn't in this widget then the
  3482.         command has no effect. Returns an empty string.
  3483.         """
  3484.         return self.selection("clear")
  3485.  
  3486.     def selection_element(self, element=None):
  3487.         """Sets or gets the currently selected element.
  3488.  
  3489.         If a spinbutton element is specified, it will be
  3490.         displayed depressed
  3491.         """
  3492.         return self.selection("element", element)
  3493.  
  3494. ###########################################################################
  3495.  
  3496. class LabelFrame(Widget):
  3497.     """labelframe widget."""
  3498.     def __init__(self, master=None, cnf={}, **kw):
  3499.         """Construct a labelframe widget with the parent MASTER.
  3500.  
  3501.         STANDARD OPTIONS
  3502.  
  3503.             borderwidth, cursor, font, foreground,
  3504.             highlightbackground, highlightcolor,
  3505.             highlightthickness, padx, pady, relief,
  3506.             takefocus, text
  3507.  
  3508.         WIDGET-SPECIFIC OPTIONS
  3509.  
  3510.             background, class, colormap, container,
  3511.             height, labelanchor, labelwidget,
  3512.             visual, width
  3513.         """
  3514.         Widget.__init__(self, master, 'labelframe', cnf, kw)
  3515.  
  3516. ########################################################################
  3517.  
  3518. class PanedWindow(Widget):
  3519.     """panedwindow widget."""
  3520.     def __init__(self, master=None, cnf={}, **kw):
  3521.         """Construct a panedwindow widget with the parent MASTER.
  3522.  
  3523.         STANDARD OPTIONS
  3524.  
  3525.             background, borderwidth, cursor, height,
  3526.             orient, relief, width
  3527.  
  3528.         WIDGET-SPECIFIC OPTIONS
  3529.  
  3530.             handlepad, handlesize, opaqueresize,
  3531.             sashcursor, sashpad, sashrelief,
  3532.             sashwidth, showhandle,
  3533.         """
  3534.         Widget.__init__(self, master, 'panedwindow', cnf, kw)
  3535.  
  3536.     def add(self, child, **kw):
  3537.         """Add a child widget to the panedwindow in a new pane.
  3538.  
  3539.         The child argument is the name of the child widget
  3540.         followed by pairs of arguments that specify how to
  3541.         manage the windows. Options may have any of the values
  3542.         accepted by the configure subcommand.
  3543.         """
  3544.         self.tk.call((self._w, 'add', child) + self._options(kw))
  3545.  
  3546.     def remove(self, child):
  3547.         """Remove the pane containing child from the panedwindow
  3548.  
  3549.         All geometry management options for child will be forgotten.
  3550.         """
  3551.         self.tk.call(self._w, 'forget', child)
  3552.     forget=remove
  3553.  
  3554.     def identify(self, x, y):
  3555.         """Identify the panedwindow component at point x, y
  3556.  
  3557.         If the point is over a sash or a sash handle, the result
  3558.         is a two element list containing the index of the sash or
  3559.         handle, and a word indicating whether it is over a sash
  3560.         or a handle, such as {0 sash} or {2 handle}. If the point
  3561.         is over any other part of the panedwindow, the result is
  3562.         an empty list.
  3563.         """
  3564.         return self.tk.call(self._w, 'identify', x, y)
  3565.  
  3566.     def proxy(self, *args):
  3567.         """Internal function."""
  3568.         return self._getints(
  3569.             self.tk.call((self._w, 'proxy') + args)) or ()
  3570.  
  3571.     def proxy_coord(self):
  3572.         """Return the x and y pair of the most recent proxy location
  3573.         """
  3574.         return self.proxy("coord")
  3575.  
  3576.     def proxy_forget(self):
  3577.         """Remove the proxy from the display.
  3578.         """
  3579.         return self.proxy("forget")
  3580.  
  3581.     def proxy_place(self, x, y):
  3582.         """Place the proxy at the given x and y coordinates.
  3583.         """
  3584.         return self.proxy("place", x, y)
  3585.  
  3586.     def sash(self, *args):
  3587.         """Internal function."""
  3588.         return self._getints(
  3589.             self.tk.call((self._w, 'sash') + args)) or ()
  3590.  
  3591.     def sash_coord(self, index):
  3592.         """Return the current x and y pair for the sash given by index.
  3593.  
  3594.         Index must be an integer between 0 and 1 less than the
  3595.         number of panes in the panedwindow. The coordinates given are
  3596.         those of the top left corner of the region containing the sash.
  3597.         pathName sash dragto index x y This command computes the
  3598.         difference between the given coordinates and the coordinates
  3599.         given to the last sash coord command for the given sash. It then
  3600.         moves that sash the computed difference. The return value is the
  3601.         empty string.
  3602.         """
  3603.         return self.sash("coord", index)
  3604.  
  3605.     def sash_mark(self, index):
  3606.         """Records x and y for the sash given by index;
  3607.  
  3608.         Used in conjunction with later dragto commands to move the sash.
  3609.         """
  3610.         return self.sash("mark", index)
  3611.  
  3612.     def sash_place(self, index, x, y):
  3613.         """Place the sash given by index at the given coordinates
  3614.         """
  3615.         return self.sash("place", index, x, y)
  3616.  
  3617.     def panecget(self, child, option):
  3618.         """Query a management option for window.
  3619.  
  3620.         Option may be any value allowed by the paneconfigure subcommand
  3621.         """
  3622.         return self.tk.call(
  3623.             (self._w, 'panecget') + (child, '-'+option))
  3624.  
  3625.     def paneconfigure(self, tagOrId, cnf=None, **kw):
  3626.         """Query or modify the management options for window.
  3627.  
  3628.         If no option is specified, returns a list describing all
  3629.         of the available options for pathName.  If option is
  3630.         specified with no value, then the command returns a list
  3631.         describing the one named option (this list will be identical
  3632.         to the corresponding sublist of the value returned if no
  3633.         option is specified). If one or more option-value pairs are
  3634.         specified, then the command modifies the given widget
  3635.         option(s) to have the given value(s); in this case the
  3636.         command returns an empty string. The following options
  3637.         are supported:
  3638.  
  3639.         after window
  3640.             Insert the window after the window specified. window
  3641.             should be the name of a window already managed by pathName.
  3642.         before window
  3643.             Insert the window before the window specified. window
  3644.             should be the name of a window already managed by pathName.
  3645.         height size
  3646.             Specify a height for the window. The height will be the
  3647.             outer dimension of the window including its border, if
  3648.             any. If size is an empty string, or if -height is not
  3649.             specified, then the height requested internally by the
  3650.             window will be used initially; the height may later be
  3651.             adjusted by the movement of sashes in the panedwindow.
  3652.             Size may be any value accepted by Tk_GetPixels.
  3653.         minsize n
  3654.             Specifies that the size of the window cannot be made
  3655.             less than n. This constraint only affects the size of
  3656.             the widget in the paned dimension -- the x dimension
  3657.             for horizontal panedwindows, the y dimension for
  3658.             vertical panedwindows. May be any value accepted by
  3659.             Tk_GetPixels.
  3660.         padx n
  3661.             Specifies a non-negative value indicating how much
  3662.             extra space to leave on each side of the window in
  3663.             the X-direction. The value may have any of the forms
  3664.             accepted by Tk_GetPixels.
  3665.         pady n
  3666.             Specifies a non-negative value indicating how much
  3667.             extra space to leave on each side of the window in
  3668.             the Y-direction. The value may have any of the forms
  3669.             accepted by Tk_GetPixels.
  3670.         sticky style
  3671.             If a window's pane is larger than the requested
  3672.             dimensions of the window, this option may be used
  3673.             to position (or stretch) the window within its pane.
  3674.             Style is a string that contains zero or more of the
  3675.             characters n, s, e or w. The string can optionally
  3676.             contains spaces or commas, but they are ignored. Each
  3677.             letter refers to a side (north, south, east, or west)
  3678.             that the window will "stick" to. If both n and s
  3679.             (or e and w) are specified, the window will be
  3680.             stretched to fill the entire height (or width) of
  3681.             its cavity.
  3682.         width size
  3683.             Specify a width for the window. The width will be
  3684.             the outer dimension of the window including its
  3685.             border, if any. If size is an empty string, or
  3686.             if -width is not specified, then the width requested
  3687.             internally by the window will be used initially; the
  3688.             width may later be adjusted by the movement of sashes
  3689.             in the panedwindow. Size may be any value accepted by
  3690.             Tk_GetPixels.
  3691.  
  3692.         """
  3693.         if cnf is None and not kw:
  3694.             cnf = {}
  3695.             for x in self.tk.split(
  3696.                 self.tk.call(self._w,
  3697.                          'paneconfigure', tagOrId)):
  3698.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  3699.             return cnf
  3700.         if type(cnf) == StringType and not kw:
  3701.             x = self.tk.split(self.tk.call(
  3702.                 self._w, 'paneconfigure', tagOrId, '-'+cnf))
  3703.             return (x[0][1:],) + x[1:]
  3704.         self.tk.call((self._w, 'paneconfigure', tagOrId) +
  3705.                  self._options(cnf, kw))
  3706.     paneconfig = paneconfigure
  3707.  
  3708.     def panes(self):
  3709.         """Returns an ordered list of the child panes."""
  3710.         return self.tk.call(self._w, 'panes')
  3711.  
  3712. ######################################################################
  3713. # Extensions:
  3714.  
  3715. class Studbutton(Button):
  3716.     def __init__(self, master=None, cnf={}, **kw):
  3717.         Widget.__init__(self, master, 'studbutton', cnf, kw)
  3718.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  3719.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  3720.         self.bind('<1>',               self.tkButtonDown)
  3721.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3722.  
  3723. class Tributton(Button):
  3724.     def __init__(self, master=None, cnf={}, **kw):
  3725.         Widget.__init__(self, master, 'tributton', cnf, kw)
  3726.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  3727.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  3728.         self.bind('<1>',               self.tkButtonDown)
  3729.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3730.         self['fg']               = self['bg']
  3731.         self['activebackground'] = self['bg']
  3732.  
  3733. ######################################################################
  3734. # Test:
  3735.  
  3736. def _test():
  3737.     root = Tk()
  3738.     text = "This is Tcl/Tk version %s" % TclVersion
  3739.     if TclVersion >= 8.1:
  3740.         try:
  3741.             text = text + unicode("\nThis should be a cedilla: \347",
  3742.                                   "iso-8859-1")
  3743.         except NameError:
  3744.             pass # no unicode support
  3745.     label = Label(root, text=text)
  3746.     label.pack()
  3747.     test = Button(root, text="Click me!",
  3748.               command=lambda root=root: root.test.configure(
  3749.                   text="[%s]" % root.test['text']))
  3750.     test.pack()
  3751.     root.test = test
  3752.     quit = Button(root, text="QUIT", command=root.destroy)
  3753.     quit.pack()
  3754.     # The following three commands are needed so the window pops
  3755.     # up on top on Windows...
  3756.     root.iconify()
  3757.     root.update()
  3758.     root.deiconify()
  3759.     root.mainloop()
  3760.  
  3761. if __name__ == '__main__':
  3762.     _test()
  3763.